r13576: This is the beginnings of moving the SAM_ACCOUNT data structure
[vlendec/samba-autobuild/.git] / source3 / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/CIFS implementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Jean François Micouleau        1998
5    Copyright (C) Gerald Carter                  2001-2003
6    Copyright (C) Shahms King                    2001
7    Copyright (C) Andrew Bartlett                2002-2003
8    Copyright (C) Stefan (metze) Metzmacher      2002-2003
9     
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23    
24 */
25
26 /* TODO:
27 *  persistent connections: if using NSS LDAP, many connections are made
28 *      however, using only one within Samba would be nice
29 *  
30 *  Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
31 *
32 *  Other LDAP based login attributes: accountExpires, etc.
33 *  (should be the domain of Samba proper, but the sam_password/struct samu
34 *  structures don't have fields for some of these attributes)
35 *
36 *  SSL is done, but can't get the certificate based authentication to work
37 *  against on my test platform (Linux 2.4, OpenLDAP 2.x)
38 */
39
40 /* NOTE: this will NOT work against an Active Directory server
41 *  due to the fact that the two password fields cannot be retrieved
42 *  from a server; recommend using security = domain in this situation
43 *  and/or winbind
44 */
45
46 #include "includes.h"
47
48 #undef DBGC_CLASS
49 #define DBGC_CLASS DBGC_PASSDB
50
51 #include <lber.h>
52 #include <ldap.h>
53
54 /*
55  * Work around versions of the LDAP client libs that don't have the OIDs
56  * defined, or have them defined under the old name.  
57  * This functionality is really a factor of the server, not the client 
58  *
59  */
60
61 #if defined(LDAP_EXOP_X_MODIFY_PASSWD) && !defined(LDAP_EXOP_MODIFY_PASSWD)
62 #define LDAP_EXOP_MODIFY_PASSWD LDAP_EXOP_X_MODIFY_PASSWD
63 #elif !defined(LDAP_EXOP_MODIFY_PASSWD)
64 #define LDAP_EXOP_MODIFY_PASSWD "1.3.6.1.4.1.4203.1.11.1"
65 #endif
66
67 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_ID) && !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
68 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID LDAP_EXOP_X_MODIFY_PASSWD_ID
69 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
70 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID        ((ber_tag_t) 0x80U)
71 #endif
72
73 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_NEW) && !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
74 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW LDAP_EXOP_X_MODIFY_PASSWD_NEW
75 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
76 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW       ((ber_tag_t) 0x82U)
77 #endif
78
79
80 #include "smbldap.h"
81
82 /**********************************************************************
83  Simple helper function to make stuff better readable
84  **********************************************************************/
85
86 static LDAP *priv2ld(struct ldapsam_privates *priv)
87 {
88         return priv->smbldap_state->ldap_struct;
89 }
90
91 /**********************************************************************
92  Get the attribute name given a user schame version.
93  **********************************************************************/
94  
95 static const char* get_userattr_key2string( int schema_ver, int key )
96 {
97         switch ( schema_ver ) {
98                 case SCHEMAVER_SAMBAACCOUNT:
99                         return get_attr_key2string( attrib_map_v22, key );
100                         
101                 case SCHEMAVER_SAMBASAMACCOUNT:
102                         return get_attr_key2string( attrib_map_v30, key );
103                         
104                 default:
105                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
106                         break;
107         }
108         return NULL;
109 }
110
111 /**********************************************************************
112  Return the list of attribute names given a user schema version.
113 **********************************************************************/
114
115 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
116 {
117         switch ( schema_ver ) {
118                 case SCHEMAVER_SAMBAACCOUNT:
119                         return get_attr_list( mem_ctx, attrib_map_v22 );
120                         
121                 case SCHEMAVER_SAMBASAMACCOUNT:
122                         return get_attr_list( mem_ctx, attrib_map_v30 );
123                 default:
124                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
125                         break;
126         }
127         
128         return NULL;
129 }
130
131 /**************************************************************************
132  Return the list of attribute names to delete given a user schema version.
133 **************************************************************************/
134
135 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
136                                               int schema_ver )
137 {
138         switch ( schema_ver ) {
139                 case SCHEMAVER_SAMBAACCOUNT:
140                         return get_attr_list( mem_ctx,
141                                               attrib_map_to_delete_v22 );
142                         
143                 case SCHEMAVER_SAMBASAMACCOUNT:
144                         return get_attr_list( mem_ctx,
145                                               attrib_map_to_delete_v30 );
146                 default:
147                         DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
148                         break;
149         }
150         
151         return NULL;
152 }
153
154
155 /*******************************************************************
156  Generate the LDAP search filter for the objectclass based on the 
157  version of the schema we are using.
158 ******************************************************************/
159
160 static const char* get_objclass_filter( int schema_ver )
161 {
162         static fstring objclass_filter;
163         
164         switch( schema_ver ) {
165                 case SCHEMAVER_SAMBAACCOUNT:
166                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
167                         break;
168                 case SCHEMAVER_SAMBASAMACCOUNT:
169                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
170                         break;
171                 default:
172                         DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
173                         break;
174         }
175         
176         return objclass_filter; 
177 }
178
179 /*****************************************************************
180  Scan a sequence number off OpenLDAP's syncrepl contextCSN
181 ******************************************************************/
182
183 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
184 {
185         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
186         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
187         LDAPMessage *msg = NULL;
188         LDAPMessage *entry = NULL;
189         TALLOC_CTX *mem_ctx;
190         char **values = NULL;
191         int rc, num_result, num_values, rid;
192         pstring suffix;
193         fstring tok;
194         const char *p;
195         const char **attrs;
196
197         /* Unfortunatly there is no proper way to detect syncrepl-support in
198          * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
199          * but do not show up in the root-DSE yet. Neither we can query the
200          * subschema-context for the syncProviderSubentry or syncConsumerSubentry
201          * objectclass. Currently we require lp_ldap_suffix() to show up as
202          * namingContext.  -  Guenther
203          */
204
205         if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
206                 return ntstatus;
207         }
208
209         if (!seq_num) {
210                 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
211                 return ntstatus;
212         }
213
214         if (!smbldap_has_naming_context(ldap_state->smbldap_state, lp_ldap_suffix())) {
215                 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
216                          "as top-level namingContext\n", lp_ldap_suffix()));
217                 return ntstatus;
218         }
219
220         mem_ctx = talloc_init("ldapsam_get_seq_num");
221
222         if (mem_ctx == NULL)
223                 return NT_STATUS_NO_MEMORY;
224
225         attrs = TALLOC_ARRAY(mem_ctx, const char *, 2);
226
227         /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
228         rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
229         if (rid > 0) {
230
231                 /* consumer syncreplCookie: */
232                 /* csn=20050126161620Z#0000001#00#00000 */
233                 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
234                 attrs[1] = NULL;
235                 pstr_sprintf( suffix, "cn=syncrepl%d,%s", rid, lp_ldap_suffix());
236
237         } else {
238
239                 /* provider contextCSN */
240                 /* 20050126161620Z#000009#00#000000 */
241                 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
242                 attrs[1] = NULL;
243                 pstr_sprintf( suffix, "cn=ldapsync,%s", lp_ldap_suffix());
244
245         }
246
247         rc = smbldap_search(ldap_state->smbldap_state, suffix,
248                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
249
250         if (rc != LDAP_SUCCESS) {
251                 goto done;
252         }
253
254         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
255         if (num_result != 1) {
256                 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
257                 goto done;
258         }
259
260         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
261         if (entry == NULL) {
262                 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
263                 goto done;
264         }
265
266         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
267         if (values == NULL) {
268                 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
269                 goto done;
270         }
271
272         num_values = ldap_count_values(values);
273         if (num_values == 0) {
274                 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
275                 goto done;
276         }
277
278         p = values[0];
279         if (!next_token(&p, tok, "#", sizeof(tok))) {
280                 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
281                 goto done;
282         }
283
284         p = tok;
285         if (!strncmp(p, "csn=", strlen("csn=")))
286                 p += strlen("csn=");
287
288         DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
289
290         *seq_num = generalized_to_unix_time(p);
291
292         /* very basic sanity check */
293         if (*seq_num <= 0) {
294                 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n", 
295                         (int)*seq_num));
296                 goto done;
297         }
298
299         ntstatus = NT_STATUS_OK;
300
301  done:
302         if (values != NULL)
303                 ldap_value_free(values);
304         if (msg != NULL)
305                 ldap_msgfree(msg);
306         if (mem_ctx)
307                 talloc_destroy(mem_ctx);
308
309         return ntstatus;
310 }
311
312 /*******************************************************************
313  Run the search by name.
314 ******************************************************************/
315
316 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state, 
317                                           const char *user,
318                                           LDAPMessage ** result,
319                                           const char **attr)
320 {
321         pstring filter;
322         char *escape_user = escape_ldap_string_alloc(user);
323
324         if (!escape_user) {
325                 return LDAP_NO_MEMORY;
326         }
327
328         /*
329          * in the filter expression, replace %u with the real name
330          * so in ldap filter, %u MUST exist :-)
331          */
332         pstr_sprintf(filter, "(&%s%s)", "(uid=%u)", 
333                 get_objclass_filter(ldap_state->schema_ver));
334
335         /* 
336          * have to use this here because $ is filtered out
337            * in pstring_sub
338          */
339         
340
341         all_string_sub(filter, "%u", escape_user, sizeof(pstring));
342         SAFE_FREE(escape_user);
343
344         return smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
345 }
346
347 /*******************************************************************
348  Run the search by rid.
349 ******************************************************************/
350
351 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state, 
352                                          uint32 rid, LDAPMessage ** result, 
353                                          const char **attr)
354 {
355         pstring filter;
356         int rc;
357
358         pstr_sprintf(filter, "(&(rid=%i)%s)", rid, 
359                 get_objclass_filter(ldap_state->schema_ver));
360         
361         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
362         
363         return rc;
364 }
365
366 /*******************************************************************
367  Run the search by SID.
368 ******************************************************************/
369
370 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state, 
371                                          const DOM_SID *sid, LDAPMessage ** result, 
372                                          const char **attr)
373 {
374         pstring filter;
375         int rc;
376         fstring sid_string;
377
378         pstr_sprintf(filter, "(&(%s=%s)%s)", 
379                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
380                 sid_to_string(sid_string, sid), 
381                 get_objclass_filter(ldap_state->schema_ver));
382                 
383         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
384         
385         return rc;
386 }
387
388 /*******************************************************************
389  Delete complete object or objectclass and attrs from
390  object found in search_result depending on lp_ldap_delete_dn
391 ******************************************************************/
392
393 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
394                                 TALLOC_CTX *mem_ctx,
395                                 LDAPMessage *entry,
396                                 const char *objectclass,
397                                 const char **attrs)
398 {
399         LDAPMod **mods = NULL;
400         char *name;
401         const char *dn;
402         BerElement *ptr = NULL;
403
404         dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
405         if (dn == NULL) {
406                 return LDAP_NO_MEMORY;
407         }
408
409         if (lp_ldap_delete_dn()) {
410                 return smbldap_delete(priv->smbldap_state, dn);
411         }
412
413         /* Ok, delete only the SAM attributes */
414         
415         for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
416              name != NULL;
417              name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
418                 const char **attrib;
419
420                 /* We are only allowed to delete the attributes that
421                    really exist. */
422
423                 for (attrib = attrs; *attrib != NULL; attrib++) {
424                         if (strequal(*attrib, name)) {
425                                 DEBUG(10, ("ldapsam_delete_entry: deleting "
426                                            "attribute %s\n", name));
427                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
428                                                 NULL);
429                         }
430                 }
431                 ldap_memfree(name);
432         }
433
434         if (ptr != NULL) {
435                 ber_free(ptr, 0);
436         }
437         
438         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
439         talloc_autofree_ldapmod(mem_ctx, mods);
440         
441         return smbldap_modify(priv->smbldap_state, dn, mods);
442 }
443                   
444 /* New Interface is being implemented here */
445
446 #if 0   /* JERRY - not uesed anymore */
447
448 /**********************************************************************
449 Initialize struct samu from an LDAP query (unix attributes only)
450 *********************************************************************/
451 static BOOL get_unix_attributes (struct ldapsam_privates *ldap_state, 
452                                 struct samu * sampass,
453                                 LDAPMessage * entry,
454                                 gid_t *gid)
455 {
456         pstring  homedir;
457         pstring  temp;
458         char **ldap_values;
459         char **values;
460
461         if ((ldap_values = ldap_get_values (ldap_state->smbldap_state->ldap_struct, entry, "objectClass")) == NULL) {
462                 DEBUG (1, ("get_unix_attributes: no objectClass! \n"));
463                 return False;
464         }
465
466         for (values=ldap_values;*values;values++) {
467                 if (strequal(*values, LDAP_OBJ_POSIXACCOUNT )) {
468                         break;
469                 }
470         }
471         
472         if (!*values) { /*end of array, no posixAccount */
473                 DEBUG(10, ("user does not have %s attributes\n", LDAP_OBJ_POSIXACCOUNT));
474                 ldap_value_free(ldap_values);
475                 return False;
476         }
477         ldap_value_free(ldap_values);
478
479         if ( !smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
480                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_UNIX_HOME), homedir) ) 
481         {
482                 return False;
483         }
484         
485         if ( !smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
486                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_GIDNUMBER), temp) )
487         {
488                 return False;
489         }
490         
491         *gid = (gid_t)atol(temp);
492
493         pdb_set_unix_homedir(sampass, homedir, PDB_SET);
494         
495         DEBUG(10, ("user has %s attributes\n", LDAP_OBJ_POSIXACCOUNT));
496         
497         return True;
498 }
499
500 #endif
501
502 static time_t ldapsam_get_entry_timestamp(
503         struct ldapsam_privates *ldap_state,
504         LDAPMessage * entry)
505 {
506         pstring temp;   
507         struct tm tm;
508
509         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
510                         get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
511                         temp))
512                 return (time_t) 0;
513
514         strptime(temp, "%Y%m%d%H%M%SZ", &tm);
515         tzset();
516         return timegm(&tm);
517 }
518
519 /**********************************************************************
520  Initialize struct samu from an LDAP query.
521  (Based on init_sam_from_buffer in pdb_tdb.c)
522 *********************************************************************/
523
524 static BOOL init_sam_from_ldap(struct ldapsam_privates *ldap_state, 
525                                 struct samu * sampass,
526                                 LDAPMessage * entry)
527 {
528         time_t  logon_time,
529                         logoff_time,
530                         kickoff_time,
531                         pass_last_set_time, 
532                         pass_can_change_time, 
533                         pass_must_change_time,
534                         ldap_entry_time,
535                         bad_password_time;
536         pstring         username, 
537                         domain,
538                         nt_username,
539                         fullname,
540                         homedir,
541                         dir_drive,
542                         logon_script,
543                         profile_path,
544                         acct_desc,
545                         workstations;
546         char            munged_dial[2048];
547         uint32          user_rid; 
548         uint8           smblmpwd[LM_HASH_LEN],
549                         smbntpwd[NT_HASH_LEN];
550         BOOL            use_samba_attrs = True;
551         uint16          acct_ctrl = 0, 
552                         logon_divs;
553         uint16          bad_password_count = 0, 
554                         logon_count = 0;
555         uint32 hours_len;
556         uint8           hours[MAX_HOURS_LEN];
557         pstring temp;
558         LOGIN_CACHE     *cache_entry = NULL;
559         uint32          pwHistLen;
560         pstring         tmpstring;
561         BOOL expand_explicit = lp_passdb_expand_explicit();
562
563         /*
564          * do a little initialization
565          */
566         username[0]     = '\0';
567         domain[0]       = '\0';
568         nt_username[0]  = '\0';
569         fullname[0]     = '\0';
570         homedir[0]      = '\0';
571         dir_drive[0]    = '\0';
572         logon_script[0] = '\0';
573         profile_path[0] = '\0';
574         acct_desc[0]    = '\0';
575         munged_dial[0]  = '\0';
576         workstations[0] = '\0';
577          
578
579         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
580                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
581                 return False;
582         }
583
584         if (priv2ld(ldap_state) == NULL) {
585                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
586                           "ldap_struct is NULL!\n"));
587                 return False;
588         }
589         
590         if (!smbldap_get_single_pstring(priv2ld(ldap_state), entry, "uid",
591                                         username)) {
592                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
593                           "this user!\n"));
594                 return False;
595         }
596
597         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
598
599         pstrcpy(nt_username, username);
600
601         pstrcpy(domain, ldap_state->domain_name);
602         
603         pdb_set_username(sampass, username, PDB_SET);
604
605         pdb_set_domain(sampass, domain, PDB_DEFAULT);
606         pdb_set_nt_username(sampass, nt_username, PDB_SET);
607
608         /* deal with different attributes between the schema first */
609         
610         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
611                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
612                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), temp)) {
613                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
614                 }
615                 
616                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
617                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_SID), temp)) {
618                         pdb_set_group_sid_from_string(sampass, temp, PDB_SET);                  
619                 } else {
620                         pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
621                 }
622         } else {
623                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
624                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), temp)) {
625                         user_rid = (uint32)atol(temp);
626                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
627                 }
628                 
629                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
630                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_RID), temp)) {
631                         pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
632                 } else {
633                         uint32 group_rid;
634                         
635                         group_rid = (uint32)atol(temp);
636                         
637                         /* for some reason, we often have 0 as a primary group RID.
638                            Make sure that we treat this just as a 'default' value */
639                            
640                         if ( group_rid > 0 )
641                                 pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
642                         else
643                                 pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
644                 }
645         }
646
647         if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
648                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
649                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
650                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
651                         username));
652                 return False;
653         }
654
655         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
656                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), temp)) {
657                 /* leave as default */
658         } else {
659                 pass_last_set_time = (time_t) atol(temp);
660                 pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
661         }
662
663         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
664                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp)) {
665                 /* leave as default */
666         } else {
667                 logon_time = (time_t) atol(temp);
668                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
669         }
670
671         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
672                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp)) {
673                 /* leave as default */
674         } else {
675                 logoff_time = (time_t) atol(temp);
676                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
677         }
678
679         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
680                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp)) {
681                 /* leave as default */
682         } else {
683                 kickoff_time = (time_t) atol(temp);
684                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
685         }
686
687         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
688                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp)) {
689                 /* leave as default */
690         } else {
691                 pass_can_change_time = (time_t) atol(temp);
692                 pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
693         }
694
695         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
696                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp)) {    
697                 /* leave as default */
698         } else {
699                 pass_must_change_time = (time_t) atol(temp);
700                 pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
701         }
702
703         /* recommend that 'gecos' and 'displayName' should refer to the same
704          * attribute OID.  userFullName depreciated, only used by Samba
705          * primary rules of LDAP: don't make a new attribute when one is already defined
706          * that fits your needs; using cn then displayName rather than 'userFullName'
707          */
708
709         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
710                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), fullname)) {
711                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
712                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_CN), fullname)) {
713                         /* leave as default */
714                 } else {
715                         pdb_set_fullname(sampass, fullname, PDB_SET);
716                 }
717         } else {
718                 pdb_set_fullname(sampass, fullname, PDB_SET);
719         }
720
721         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
722                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), dir_drive)) 
723         {
724                 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
725         } else {
726                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
727         }
728
729         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
730                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), homedir)) 
731         {
732                 pdb_set_homedir( sampass, 
733                         talloc_sub_basic(sampass, username, lp_logon_home()),
734                         PDB_DEFAULT );
735         } else {
736                 pstrcpy( tmpstring, homedir );
737                 if (expand_explicit) {
738                         standard_sub_basic( username, tmpstring,
739                                             sizeof(tmpstring) );
740                 }
741                 pdb_set_homedir(sampass, tmpstring, PDB_SET);
742         }
743
744         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
745                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), logon_script)) 
746         {
747                 pdb_set_logon_script( sampass, 
748                         talloc_sub_basic(sampass, username, lp_logon_script()), 
749                         PDB_DEFAULT );
750         } else {
751                 pstrcpy( tmpstring, logon_script );
752                 if (expand_explicit) {
753                         standard_sub_basic( username, tmpstring,
754                                             sizeof(tmpstring) );
755                 }
756                 pdb_set_logon_script(sampass, tmpstring, PDB_SET);
757         }
758
759         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
760                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), profile_path)) 
761         {
762                 pdb_set_profile_path( sampass, 
763                         talloc_sub_basic( sampass, username, lp_logon_path()),
764                         PDB_DEFAULT );
765         } else {
766                 pstrcpy( tmpstring, profile_path );
767                 if (expand_explicit) {
768                         standard_sub_basic( username, tmpstring,
769                                             sizeof(tmpstring) );
770                 }
771                 pdb_set_profile_path(sampass, tmpstring, PDB_SET);
772         }
773
774         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
775                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), acct_desc)) 
776         {
777                 /* leave as default */
778         } else {
779                 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
780         }
781
782         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
783                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), workstations)) {
784                 /* leave as default */;
785         } else {
786                 pdb_set_workstations(sampass, workstations, PDB_SET);
787         }
788
789         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
790                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), munged_dial, sizeof(munged_dial))) {
791                 /* leave as default */;
792         } else {
793                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
794         }
795         
796         /* FIXME: hours stuff should be cleaner */
797         
798         logon_divs = 168;
799         hours_len = 21;
800         memset(hours, 0xff, hours_len);
801
802         if (ldap_state->is_nds_ldap) {
803                 char *user_dn;
804                 size_t pwd_len;
805                 char clear_text_pw[512];
806    
807                 /* Make call to Novell eDirectory ldap extension to get clear text password.
808                         NOTE: This will only work if we have an SSL connection to eDirectory. */
809                 user_dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
810                 if (user_dn != NULL) {
811                         DEBUG(3, ("init_sam_from_ldap: smbldap_get_dn(%s) returned '%s'\n", username, user_dn));
812
813                         pwd_len = sizeof(clear_text_pw);
814                         if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
815                                 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
816                                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
817                                         return False;
818                                 ZERO_STRUCT(smblmpwd);
819                                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
820                                         return False;
821                                 ZERO_STRUCT(smbntpwd);
822                                 use_samba_attrs = False;
823                         }
824                 } else {
825                         DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
826                 }
827         }
828
829         if (use_samba_attrs) {
830                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry, 
831                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), temp)) {
832                         /* leave as default */
833                 } else {
834                         pdb_gethexpwd(temp, smblmpwd);
835                         memset((char *)temp, '\0', strlen(temp)+1);
836                         if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
837                                 return False;
838                         ZERO_STRUCT(smblmpwd);
839                 }
840
841                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
842                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), temp)) {
843                         /* leave as default */
844                 } else {
845                         pdb_gethexpwd(temp, smbntpwd);
846                         memset((char *)temp, '\0', strlen(temp)+1);
847                         if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
848                                 return False;
849                         ZERO_STRUCT(smbntpwd);
850                 }
851         }
852
853         pwHistLen = 0;
854
855         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
856         if (pwHistLen > 0){
857                 uint8 *pwhist = NULL;
858                 int i;
859
860                 /* We can only store (sizeof(pstring)-1)/64 password history entries. */
861                 pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
862
863                 if ((pwhist = SMB_MALLOC(pwHistLen * PW_HISTORY_ENTRY_LEN)) == NULL){
864                         DEBUG(0, ("init_sam_from_ldap: malloc failed!\n"));
865                         return False;
866                 }
867                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
868
869                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry, 
870                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), temp)) {
871                         /* leave as default - zeros */
872                 } else {
873                         BOOL hex_failed = False;
874                         for (i = 0; i < pwHistLen; i++){
875                                 /* Get the 16 byte salt. */
876                                 if (!pdb_gethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
877                                         hex_failed = True;
878                                         break;
879                                 }
880                                 /* Get the 16 byte MD5 hash of salt+passwd. */
881                                 if (!pdb_gethexpwd(&temp[(i*64)+32],
882                                                 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN])) {
883                                         hex_failed = True;
884                                         break;
885                                 }
886                         }
887                         if (hex_failed) {
888                                 DEBUG(0,("init_sam_from_ldap: Failed to get password history for user %s\n",
889                                         username));
890                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
891                         }
892                 }
893                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
894                         SAFE_FREE(pwhist);
895                         return False;
896                 }
897                 SAFE_FREE(pwhist);
898         }
899
900         if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
901                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), temp)) {
902                 acct_ctrl |= ACB_NORMAL;
903         } else {
904                 acct_ctrl = pdb_decode_acct_ctrl(temp);
905
906                 if (acct_ctrl == 0)
907                         acct_ctrl |= ACB_NORMAL;
908
909                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
910         }
911
912         pdb_set_hours_len(sampass, hours_len, PDB_SET);
913         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
914
915         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
916                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_COUNT), temp)) {
917                         /* leave as default */
918         } else {
919                 bad_password_count = (uint32) atol(temp);
920                 pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
921         }
922
923         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
924                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_TIME), temp)) {
925                 /* leave as default */
926         } else {
927                 bad_password_time = (time_t) atol(temp);
928                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
929         }
930
931
932         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
933                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_COUNT), temp)) {
934                         /* leave as default */
935         } else {
936                 logon_count = (uint32) atol(temp);
937                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
938         }
939
940         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
941
942         if(!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
943                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_HOURS), temp)) {
944                         /* leave as default */
945         } else {
946                 pdb_gethexhours(temp, hours);
947                 memset((char *)temp, '\0', strlen(temp) +1);
948                 pdb_set_hours(sampass, hours, PDB_SET);
949                 ZERO_STRUCT(hours);
950         }
951
952         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
953                 if (smbldap_get_single_pstring(priv2ld(ldap_state), entry,
954                                                "uidNumber", temp)) {
955                         /* We've got a uid, feed the cache */
956                         uid_t uid = strtoul(temp, NULL, 10);
957                         store_uid_sid_cache(pdb_get_user_sid(sampass), uid);
958                 }
959         }
960
961         /* check the timestamp of the cache vs ldap entry */
962         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state, 
963                                                             entry)))
964                 return True;
965
966         /* see if we have newer updates */
967         if (!(cache_entry = login_cache_read(sampass))) {
968                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
969                            (unsigned int)pdb_get_bad_password_count(sampass),
970                            (unsigned int)pdb_get_bad_password_time(sampass)));
971                 return True;
972         }
973
974         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n", 
975                   (unsigned int)ldap_entry_time, (unsigned int)cache_entry->entry_timestamp, 
976                   (unsigned int)cache_entry->bad_password_time));
977
978         if (ldap_entry_time > cache_entry->entry_timestamp) {
979                 /* cache is older than directory , so
980                    we need to delete the entry but allow the 
981                    fields to be written out */
982                 login_cache_delentry(sampass);
983         } else {
984                 /* read cache in */
985                 pdb_set_acct_ctrl(sampass, 
986                                   pdb_get_acct_ctrl(sampass) | 
987                                   (cache_entry->acct_ctrl & ACB_AUTOLOCK),
988                                   PDB_SET);
989                 pdb_set_bad_password_count(sampass, 
990                                            cache_entry->bad_password_count, 
991                                            PDB_SET);
992                 pdb_set_bad_password_time(sampass, 
993                                           cache_entry->bad_password_time, 
994                                           PDB_SET);
995         }
996
997         SAFE_FREE(cache_entry);
998         return True;
999 }
1000
1001 /**********************************************************************
1002  Initialize the ldap db from a struct samu. Called on update.
1003  (Based on init_buffer_from_sam in pdb_tdb.c)
1004 *********************************************************************/
1005
1006 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state, 
1007                                 LDAPMessage *existing,
1008                                 LDAPMod *** mods, struct samu * sampass,
1009                                 BOOL (*need_update)(const struct samu *,
1010                                                     enum pdb_elements))
1011 {
1012         pstring temp;
1013         uint32 rid;
1014
1015         if (mods == NULL || sampass == NULL) {
1016                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1017                 return False;
1018         }
1019
1020         *mods = NULL;
1021
1022         /* 
1023          * took out adding "objectclass: sambaAccount"
1024          * do this on a per-mod basis
1025          */
1026         if (need_update(sampass, PDB_USERNAME))
1027                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1028                               "uid", pdb_get_username(sampass));
1029
1030         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1031
1032         /* only update the RID if we actually need to */
1033         if (need_update(sampass, PDB_USERSID)) {
1034                 fstring sid_string;
1035                 fstring dom_sid_string;
1036                 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
1037                 
1038                 switch ( ldap_state->schema_ver ) {
1039                         case SCHEMAVER_SAMBAACCOUNT:
1040                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
1041                                         DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
1042                                                 sid_to_string(sid_string, user_sid), 
1043                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
1044                                         return False;
1045                                 }
1046                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
1047                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1048                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
1049                                         temp);
1050                                 break;
1051                                 
1052                         case SCHEMAVER_SAMBASAMACCOUNT:
1053                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1054                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
1055                                         sid_to_string(sid_string, user_sid));                                 
1056                                 break;
1057                                 
1058                         default:
1059                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1060                                 break;
1061                 }               
1062         }
1063
1064         /* we don't need to store the primary group RID - so leaving it
1065            'free' to hang off the unix primary group makes life easier */
1066
1067         if (need_update(sampass, PDB_GROUPSID)) {
1068                 fstring sid_string;
1069                 fstring dom_sid_string;
1070                 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
1071                 
1072                 switch ( ldap_state->schema_ver ) {
1073                         case SCHEMAVER_SAMBAACCOUNT:
1074                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
1075                                         DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1076                                                 sid_to_string(sid_string, group_sid),
1077                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
1078                                         return False;
1079                                 }
1080
1081                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
1082                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1083                                         get_userattr_key2string(ldap_state->schema_ver, 
1084                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
1085                                 break;
1086                                 
1087                         case SCHEMAVER_SAMBASAMACCOUNT:
1088                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1089                                         get_userattr_key2string(ldap_state->schema_ver, 
1090                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_string(sid_string, group_sid));
1091                                 break;
1092                                 
1093                         default:
1094                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1095                                 break;
1096                 }
1097                 
1098         }
1099         
1100         /* displayName, cn, and gecos should all be the same
1101          *  most easily accomplished by giving them the same OID
1102          *  gecos isn't set here b/c it should be handled by the 
1103          *  add-user script
1104          *  We change displayName only and fall back to cn if
1105          *  it does not exist.
1106          */
1107
1108         if (need_update(sampass, PDB_FULLNAME))
1109                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1110                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
1111                         pdb_get_fullname(sampass));
1112
1113         if (need_update(sampass, PDB_ACCTDESC))
1114                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1115                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
1116                         pdb_get_acct_desc(sampass));
1117
1118         if (need_update(sampass, PDB_WORKSTATIONS))
1119                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1120                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
1121                         pdb_get_workstations(sampass));
1122         
1123         if (need_update(sampass, PDB_MUNGEDDIAL))
1124                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1125                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
1126                         pdb_get_munged_dial(sampass));
1127         
1128         if (need_update(sampass, PDB_SMBHOME))
1129                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1130                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
1131                         pdb_get_homedir(sampass));
1132                         
1133         if (need_update(sampass, PDB_DRIVE))
1134                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1135                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
1136                         pdb_get_dir_drive(sampass));
1137
1138         if (need_update(sampass, PDB_LOGONSCRIPT))
1139                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1140                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1141                         pdb_get_logon_script(sampass));
1142
1143         if (need_update(sampass, PDB_PROFILE))
1144                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1145                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1146                         pdb_get_profile_path(sampass));
1147
1148         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
1149         if (need_update(sampass, PDB_LOGONTIME))
1150                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1151                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1152
1153         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
1154         if (need_update(sampass, PDB_LOGOFFTIME))
1155                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1156                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1157
1158         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
1159         if (need_update(sampass, PDB_KICKOFFTIME))
1160                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1161                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1162
1163         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
1164         if (need_update(sampass, PDB_CANCHANGETIME))
1165                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1166                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1167
1168         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
1169         if (need_update(sampass, PDB_MUSTCHANGETIME))
1170                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1171                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1172
1173
1174         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1175                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1176
1177                 if (need_update(sampass, PDB_LMPASSWD)) {
1178                         const uchar *lm_pw =  pdb_get_lanman_passwd(sampass);
1179                         if (lm_pw) {
1180                                 pdb_sethexpwd(temp, lm_pw,
1181                                               pdb_get_acct_ctrl(sampass));
1182                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1183                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1184                                                  temp);
1185                         } else {
1186                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1187                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1188                                                  NULL);
1189                         }
1190                 }
1191                 if (need_update(sampass, PDB_NTPASSWD)) {
1192                         const uchar *nt_pw =  pdb_get_nt_passwd(sampass);
1193                         if (nt_pw) {
1194                                 pdb_sethexpwd(temp, nt_pw,
1195                                               pdb_get_acct_ctrl(sampass));
1196                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1197                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1198                                                  temp);
1199                         } else {
1200                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1201                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1202                                                  NULL);
1203                         }
1204                 }
1205
1206                 if (need_update(sampass, PDB_PWHISTORY)) {
1207                         uint32 pwHistLen = 0;
1208                         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
1209                         if (pwHistLen == 0) {
1210                                 /* Remove any password history from the LDAP store. */
1211                                 memset(temp, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1212                                 temp[64] = '\0';
1213                         } else {
1214                                 int i; 
1215                                 uint32 currHistLen = 0;
1216                                 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1217                                 if (pwhist != NULL) {
1218                                         /* We can only store (sizeof(pstring)-1)/64 password history entries. */
1219                                         pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
1220                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1221                                                 /* Store the salt. */
1222                                                 pdb_sethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1223                                                 /* Followed by the md5 hash of salt + md4 hash */
1224                                                 pdb_sethexpwd(&temp[(i*64)+32],
1225                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1226                                                 DEBUG(100, ("temp=%s\n", temp));
1227                                         }
1228                                 } 
1229                         }
1230                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1231                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1232                                          temp);
1233                 }
1234
1235                 if (need_update(sampass, PDB_PASSLASTSET)) {
1236                         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
1237                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1238                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1239                                 temp);
1240                 }
1241         }
1242
1243         if (need_update(sampass, PDB_HOURS)) {
1244                 const uint8 *hours = pdb_get_hours(sampass);
1245                 if (hours) {
1246                         pdb_sethexhours(temp, hours);
1247                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1248                                 existing,
1249                                 mods,
1250                                 get_userattr_key2string(ldap_state->schema_ver,
1251                                                 LDAP_ATTR_LOGON_HOURS),
1252                                 temp);
1253                 }
1254         }
1255
1256         if (need_update(sampass, PDB_ACCTCTRL))
1257                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1258                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1259                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1260
1261         /* password lockout cache: 
1262            - If we are now autolocking or clearing, we write to ldap
1263            - If we are clearing, we delete the cache entry
1264            - If the count is > 0, we update the cache
1265
1266            This even means when autolocking, we cache, just in case the
1267            update doesn't work, and we have to cache the autolock flag */
1268
1269         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1270             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1271                 uint16 badcount = pdb_get_bad_password_count(sampass);
1272                 time_t badtime = pdb_get_bad_password_time(sampass);
1273                 uint32 pol;
1274                 pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1275
1276                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1277                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1278
1279                 if ((badcount >= pol) || (badcount == 0)) {
1280                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1281                                 (unsigned int)badcount, (unsigned int)badtime));
1282                         slprintf (temp, sizeof (temp) - 1, "%li", (long)badcount);
1283                         smbldap_make_mod(
1284                                 ldap_state->smbldap_state->ldap_struct,
1285                                 existing, mods, 
1286                                 get_userattr_key2string(
1287                                         ldap_state->schema_ver, 
1288                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1289                                 temp);
1290
1291                         slprintf (temp, sizeof (temp) - 1, "%li", badtime);
1292                         smbldap_make_mod(
1293                                 ldap_state->smbldap_state->ldap_struct, 
1294                                 existing, mods,
1295                                 get_userattr_key2string(
1296                                         ldap_state->schema_ver, 
1297                                         LDAP_ATTR_BAD_PASSWORD_TIME), 
1298                                 temp);
1299                 }
1300                 if (badcount == 0) {
1301                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1302                         login_cache_delentry(sampass);
1303                 } else {
1304                         LOGIN_CACHE cache_entry;
1305
1306                         cache_entry.entry_timestamp = time(NULL);
1307                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1308                         cache_entry.bad_password_count = badcount;
1309                         cache_entry.bad_password_time = badtime;
1310
1311                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1312                         login_cache_write(sampass, cache_entry);
1313                 }
1314         }
1315
1316         return True;
1317 }
1318
1319 /**********************************************************************
1320  Connect to LDAP server for password enumeration.
1321 *********************************************************************/
1322
1323 static NTSTATUS ldapsam_setsampwent(struct pdb_methods *my_methods, BOOL update, uint16 acb_mask)
1324 {
1325         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1326         int rc;
1327         pstring filter, suffix;
1328         const char **attr_list;
1329         BOOL machine_mask = False, user_mask = False;
1330
1331         pstr_sprintf( filter, "(&%s%s)", "(uid=%u)", 
1332                 get_objclass_filter(ldap_state->schema_ver));
1333         all_string_sub(filter, "%u", "*", sizeof(pstring));
1334
1335         machine_mask    = ((acb_mask != 0) && (acb_mask & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)));
1336         user_mask       = ((acb_mask != 0) && (acb_mask & ACB_NORMAL));
1337
1338         if (machine_mask) {
1339                 pstrcpy(suffix, lp_ldap_machine_suffix());
1340         } else if (user_mask) {
1341                 pstrcpy(suffix, lp_ldap_user_suffix());
1342         } else {
1343                 pstrcpy(suffix, lp_ldap_suffix());
1344         }
1345
1346         DEBUG(10,("ldapsam_setsampwent: LDAP Query for acb_mask 0x%x will use suffix %s\n", 
1347                 acb_mask, suffix));
1348
1349         attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1350         rc = smbldap_search(ldap_state->smbldap_state, suffix, LDAP_SCOPE_SUBTREE, filter, 
1351                             attr_list, 0, &ldap_state->result);
1352         TALLOC_FREE( attr_list );
1353
1354         if (rc != LDAP_SUCCESS) {
1355                 DEBUG(0, ("ldapsam_setsampwent: LDAP search failed: %s\n", ldap_err2string(rc)));
1356                 DEBUG(3, ("ldapsam_setsampwent: Query was: %s, %s\n", suffix, filter));
1357                 ldap_msgfree(ldap_state->result);
1358                 ldap_state->result = NULL;
1359                 return NT_STATUS_UNSUCCESSFUL;
1360         }
1361
1362         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base %s\n",
1363                 ldap_count_entries(ldap_state->smbldap_state->ldap_struct, 
1364                 ldap_state->result), suffix));
1365
1366         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
1367                                  ldap_state->result);
1368         ldap_state->index = 0;
1369
1370         return NT_STATUS_OK;
1371 }
1372
1373 /**********************************************************************
1374  End enumeration of the LDAP password list.
1375 *********************************************************************/
1376
1377 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1378 {
1379         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1380         if (ldap_state->result) {
1381                 ldap_msgfree(ldap_state->result);
1382                 ldap_state->result = NULL;
1383         }
1384 }
1385
1386 /**********************************************************************
1387 Get the next entry in the LDAP password database.
1388 *********************************************************************/
1389
1390 static NTSTATUS ldapsam_getsampwent(struct pdb_methods *my_methods,
1391                                     struct samu *user)
1392 {
1393         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1394         struct ldapsam_privates *ldap_state =
1395                 (struct ldapsam_privates *)my_methods->private_data;
1396         BOOL bret = False;
1397
1398         while (!bret) {
1399                 if (!ldap_state->entry)
1400                         return ret;
1401                 
1402                 ldap_state->index++;
1403                 bret = init_sam_from_ldap(ldap_state, user, ldap_state->entry);
1404                 
1405                 ldap_state->entry = ldap_next_entry(priv2ld(ldap_state),
1406                                                     ldap_state->entry); 
1407         }
1408
1409         return NT_STATUS_OK;
1410 }
1411
1412 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1413                         const char *new_attr)
1414 {
1415         int i;
1416
1417         if (new_attr == NULL) {
1418                 return;
1419         }
1420
1421         for (i=0; (*attr_list)[i] != NULL; i++) {
1422                 ;
1423         }
1424
1425         (*attr_list) = TALLOC_REALLOC_ARRAY(mem_ctx, (*attr_list),
1426                                             const char *,  i+2);
1427         SMB_ASSERT((*attr_list) != NULL);
1428         (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1429         (*attr_list)[i+1] = NULL;
1430 }
1431
1432 /**********************************************************************
1433 Get struct samu entry from LDAP by username.
1434 *********************************************************************/
1435
1436 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1437 {
1438         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1439         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1440         LDAPMessage *result = NULL;
1441         LDAPMessage *entry = NULL;
1442         int count;
1443         const char ** attr_list;
1444         int rc;
1445         
1446         attr_list = get_userattr_list( user, ldap_state->schema_ver );
1447         append_attr(user, &attr_list,
1448                     get_userattr_key2string(ldap_state->schema_ver,
1449                                             LDAP_ATTR_MOD_TIMESTAMP));
1450         append_attr(user, &attr_list, "uidNumber");
1451         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1452                                            attr_list);
1453         TALLOC_FREE( attr_list );
1454
1455         if ( rc != LDAP_SUCCESS ) 
1456                 return NT_STATUS_NO_SUCH_USER;
1457         
1458         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1459         
1460         if (count < 1) {
1461                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1462                 ldap_msgfree(result);
1463                 return NT_STATUS_NO_SUCH_USER;
1464         } else if (count > 1) {
1465                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1466                 ldap_msgfree(result);
1467                 return NT_STATUS_NO_SUCH_USER;
1468         }
1469
1470         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1471         if (entry) {
1472                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1473                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1474                         ldap_msgfree(result);
1475                         return NT_STATUS_NO_SUCH_USER;
1476                 }
1477                 pdb_set_backend_private_data(user, result, NULL,
1478                                              my_methods, PDB_CHANGED);
1479                 talloc_autofree_ldapmsg(user, result);
1480                 ret = NT_STATUS_OK;
1481         } else {
1482                 ldap_msgfree(result);
1483         }
1484         return ret;
1485 }
1486
1487 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1488                                    const DOM_SID *sid, LDAPMessage **result) 
1489 {
1490         int rc = -1;
1491         const char ** attr_list;
1492         uint32 rid;
1493
1494         switch ( ldap_state->schema_ver ) {
1495                 case SCHEMAVER_SAMBASAMACCOUNT: {
1496                         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1497                         if (tmp_ctx == NULL) {
1498                                 return LDAP_NO_MEMORY;
1499                         }
1500
1501                         attr_list = get_userattr_list(tmp_ctx,
1502                                                       ldap_state->schema_ver);
1503                         append_attr(tmp_ctx, &attr_list,
1504                                     get_userattr_key2string(
1505                                             ldap_state->schema_ver,
1506                                             LDAP_ATTR_MOD_TIMESTAMP));
1507                         append_attr(tmp_ctx, &attr_list, "uidNumber");
1508                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1509                                                           result, attr_list);
1510                         TALLOC_FREE(tmp_ctx);
1511
1512                         if ( rc != LDAP_SUCCESS ) 
1513                                 return rc;
1514                         break;
1515                 }
1516                         
1517                 case SCHEMAVER_SAMBAACCOUNT:
1518                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1519                                 return rc;
1520                         }
1521                 
1522                         attr_list = get_userattr_list(NULL,
1523                                                       ldap_state->schema_ver);
1524                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1525                         TALLOC_FREE( attr_list );
1526
1527                         if ( rc != LDAP_SUCCESS ) 
1528                                 return rc;
1529                         break;
1530         }
1531         return rc;
1532 }
1533
1534 /**********************************************************************
1535  Get struct samu entry from LDAP by SID.
1536 *********************************************************************/
1537
1538 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1539 {
1540         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1541         LDAPMessage *result = NULL;
1542         LDAPMessage *entry = NULL;
1543         int count;
1544         int rc;
1545         fstring sid_string;
1546
1547         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1548                                           sid, &result); 
1549         if (rc != LDAP_SUCCESS)
1550                 return NT_STATUS_NO_SUCH_USER;
1551
1552         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1553         
1554         if (count < 1) {
1555                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] count=%d\n", sid_to_string(sid_string, sid),
1556                        count));
1557                 ldap_msgfree(result);
1558                 return NT_STATUS_NO_SUCH_USER;
1559         }  else if (count > 1) {
1560                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID [%s]. Failing. count=%d\n", sid_to_string(sid_string, sid),
1561                        count));
1562                 ldap_msgfree(result);
1563                 return NT_STATUS_NO_SUCH_USER;
1564         }
1565
1566         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1567         if (!entry) {
1568                 ldap_msgfree(result);
1569                 return NT_STATUS_NO_SUCH_USER;
1570         }
1571
1572         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1573                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1574                 ldap_msgfree(result);
1575                 return NT_STATUS_NO_SUCH_USER;
1576         }
1577
1578         pdb_set_backend_private_data(user, result, NULL,
1579                                      my_methods, PDB_CHANGED);
1580         talloc_autofree_ldapmsg(user, result);
1581         return NT_STATUS_OK;
1582 }       
1583
1584 static BOOL ldapsam_can_pwchange_exop(struct smbldap_state *ldap_state)
1585 {
1586         return smbldap_has_extension(ldap_state, LDAP_EXOP_MODIFY_PASSWD);
1587 }
1588
1589 /********************************************************************
1590  Do the actual modification - also change a plaintext passord if 
1591  it it set.
1592 **********************************************************************/
1593
1594 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1595                                      struct samu *newpwd, char *dn,
1596                                      LDAPMod **mods, int ldap_op, 
1597                                      BOOL (*need_update)(const struct samu *, enum pdb_elements))
1598 {
1599         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1600         int rc;
1601         
1602         if (!my_methods || !newpwd || !dn) {
1603                 return NT_STATUS_INVALID_PARAMETER;
1604         }
1605         
1606         if (!mods) {
1607                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1608                 /* may be password change below however */
1609         } else {
1610                 switch(ldap_op) {
1611                         case LDAP_MOD_ADD: 
1612                                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1613                                                 "objectclass", 
1614                                                 LDAP_OBJ_ACCOUNT);
1615                                 rc = smbldap_add(ldap_state->smbldap_state, 
1616                                                  dn, mods);
1617                                 break;
1618                         case LDAP_MOD_REPLACE: 
1619                                 rc = smbldap_modify(ldap_state->smbldap_state, 
1620                                                     dn ,mods);
1621                                 break;
1622                         default:        
1623                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n", 
1624                                          ldap_op));
1625                                 return NT_STATUS_INVALID_PARAMETER;
1626                 }
1627                 
1628                 if (rc!=LDAP_SUCCESS) {
1629                         return NT_STATUS_UNSUCCESSFUL;
1630                 }  
1631         }
1632         
1633         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1634                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1635                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1636                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1637                 BerElement *ber;
1638                 struct berval *bv;
1639                 char *retoid = NULL;
1640                 struct berval *retdata = NULL;
1641                 char *utf8_password;
1642                 char *utf8_dn;
1643
1644                 if (!ldap_state->is_nds_ldap) {
1645                         if (!ldapsam_can_pwchange_exop(ldap_state->smbldap_state)) {
1646                                 DEBUG(2, ("ldap password change requested, but LDAP "
1647                                           "server does not support it -- ignoring\n"));
1648                                 return NT_STATUS_OK;
1649                         }
1650                 }
1651
1652                 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1653                         return NT_STATUS_NO_MEMORY;
1654                 }
1655
1656                 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1657                         return NT_STATUS_NO_MEMORY;
1658                 }
1659
1660                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1661                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1662                         SAFE_FREE(utf8_password);
1663                         return NT_STATUS_UNSUCCESSFUL;
1664                 }
1665
1666                 ber_printf (ber, "{");
1667                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn);
1668                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password);
1669                 ber_printf (ber, "N}");
1670
1671                 if ((rc = ber_flatten (ber, &bv))<0) {
1672                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1673                         ber_free(ber,1);
1674                         SAFE_FREE(utf8_dn);
1675                         SAFE_FREE(utf8_password);
1676                         return NT_STATUS_UNSUCCESSFUL;
1677                 }
1678                 
1679                 SAFE_FREE(utf8_dn);
1680                 SAFE_FREE(utf8_password);
1681                 ber_free(ber, 1);
1682
1683                 if (!ldap_state->is_nds_ldap) {
1684                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1685                                                         LDAP_EXOP_MODIFY_PASSWD,
1686                                                         bv, NULL, NULL, &retoid, 
1687                                                         &retdata);
1688                 } else {
1689                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1690                                                         pdb_get_plaintext_passwd(newpwd));
1691                 }
1692                 if (rc != LDAP_SUCCESS) {
1693                         char *ld_error = NULL;
1694
1695                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1696                                 DEBUG(3, ("Could not set userPassword "
1697                                           "attribute due to an objectClass "
1698                                           "violation -- ignoring\n"));
1699                                 ber_bvfree(bv);
1700                                 return NT_STATUS_OK;
1701                         }
1702
1703                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1704                                         &ld_error);
1705                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1706                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1707                         SAFE_FREE(ld_error);
1708                         ber_bvfree(bv);
1709                         return NT_STATUS_UNSUCCESSFUL;
1710                 } else {
1711                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1712 #ifdef DEBUG_PASSWORD
1713                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1714 #endif    
1715                         if (retdata)
1716                                 ber_bvfree(retdata);
1717                         if (retoid)
1718                                 ldap_memfree(retoid);
1719                 }
1720                 ber_bvfree(bv);
1721         }
1722         return NT_STATUS_OK;
1723 }
1724
1725 /**********************************************************************
1726  Delete entry from LDAP for username.
1727 *********************************************************************/
1728
1729 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1730                                            struct samu * sam_acct)
1731 {
1732         struct ldapsam_privates *priv =
1733                 (struct ldapsam_privates *)my_methods->private_data;
1734         const char *sname;
1735         int rc;
1736         LDAPMessage *msg, *entry;
1737         NTSTATUS result = NT_STATUS_NO_MEMORY;
1738         const char **attr_list;
1739         TALLOC_CTX *mem_ctx;
1740
1741         if (!sam_acct) {
1742                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1743                 return NT_STATUS_INVALID_PARAMETER;
1744         }
1745
1746         sname = pdb_get_username(sam_acct);
1747
1748         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1749                   "LDAP.\n", sname));
1750
1751         mem_ctx = talloc_new(NULL);
1752         if (mem_ctx == NULL) {
1753                 DEBUG(0, ("talloc_new failed\n"));
1754                 goto done;
1755         }
1756
1757         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1758         if (attr_list == NULL) {
1759                 goto done;
1760         }
1761
1762         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1763
1764         if ((rc != LDAP_SUCCESS) ||
1765             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1766             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1767                 DEBUG(5, ("Could not find user %s\n", sname));
1768                 result = NT_STATUS_NO_SUCH_USER;
1769                 goto done;
1770         }
1771         
1772         rc = ldapsam_delete_entry(
1773                 priv, mem_ctx, entry,
1774                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1775                 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1776                 attr_list);
1777
1778         result = (rc == LDAP_SUCCESS) ?
1779                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1780
1781  done:
1782         TALLOC_FREE(mem_ctx);
1783         return result;
1784 }
1785
1786 /**********************************************************************
1787  Helper function to determine for update_sam_account whether
1788  we need LDAP modification.
1789 *********************************************************************/
1790
1791 static BOOL element_is_changed(const struct samu *sampass,
1792                                enum pdb_elements element)
1793 {
1794         return IS_SAM_CHANGED(sampass, element);
1795 }
1796
1797 /**********************************************************************
1798  Update struct samu.
1799 *********************************************************************/
1800
1801 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1802 {
1803         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1804         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1805         int rc = 0;
1806         char *dn;
1807         LDAPMessage *result = NULL;
1808         LDAPMessage *entry = NULL;
1809         LDAPMod **mods = NULL;
1810         const char **attr_list;
1811
1812         result = pdb_get_backend_private_data(newpwd, my_methods);
1813         if (!result) {
1814                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1815                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1816                 TALLOC_FREE( attr_list );
1817                 if (rc != LDAP_SUCCESS) {
1818                         return NT_STATUS_UNSUCCESSFUL;
1819                 }
1820                 pdb_set_backend_private_data(newpwd, result, NULL,
1821                                              my_methods, PDB_CHANGED);
1822                 talloc_autofree_ldapmsg(newpwd, result);
1823         }
1824
1825         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1826                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1827                 return NT_STATUS_UNSUCCESSFUL;
1828         }
1829
1830         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1831         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1832         if (!dn) {
1833                 return NT_STATUS_UNSUCCESSFUL;
1834         }
1835
1836         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1837
1838         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1839                                 element_is_changed)) {
1840                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1841                 SAFE_FREE(dn);
1842                 if (mods != NULL)
1843                         ldap_mods_free(mods,True);
1844                 return NT_STATUS_UNSUCCESSFUL;
1845         }
1846         
1847         if (mods == NULL) {
1848                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1849                          pdb_get_username(newpwd)));
1850                 SAFE_FREE(dn);
1851                 return NT_STATUS_OK;
1852         }
1853         
1854         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1855         ldap_mods_free(mods,True);
1856         SAFE_FREE(dn);
1857
1858         if (!NT_STATUS_IS_OK(ret)) {
1859                 return ret;
1860         }
1861
1862         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1863                   pdb_get_username(newpwd)));
1864         return NT_STATUS_OK;
1865 }
1866
1867 /***************************************************************************
1868  Renames a struct samu
1869  - The "rename user script" has full responsibility for changing everything
1870 ***************************************************************************/
1871
1872 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1873                                            struct samu *old_acct, 
1874                                            const char *newname)
1875 {
1876         const char *oldname;
1877         int rc;
1878         pstring rename_script;
1879
1880         if (!old_acct) {
1881                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1882                 return NT_STATUS_INVALID_PARAMETER;
1883         }
1884         if (!newname) {
1885                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1886                 return NT_STATUS_INVALID_PARAMETER;
1887         }
1888                 
1889         oldname = pdb_get_username(old_acct);
1890
1891         /* rename the posix user */
1892         pstrcpy(rename_script, lp_renameuser_script());
1893
1894         if (!(*rename_script))
1895                 return NT_STATUS_ACCESS_DENIED;
1896
1897         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n", 
1898                    oldname, newname));
1899
1900         pstring_sub(rename_script, "%unew", newname);
1901         pstring_sub(rename_script, "%uold", oldname);
1902         rc = smbrun(rename_script, NULL);
1903
1904         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n", 
1905                           rename_script, rc));
1906
1907         if (rc)
1908                 return NT_STATUS_UNSUCCESSFUL;
1909
1910         return NT_STATUS_OK;
1911 }
1912
1913 /**********************************************************************
1914  Helper function to determine for update_sam_account whether
1915  we need LDAP modification.
1916  *********************************************************************/
1917
1918 static BOOL element_is_set_or_changed(const struct samu *sampass,
1919                                       enum pdb_elements element)
1920 {
1921         return (IS_SAM_SET(sampass, element) ||
1922                 IS_SAM_CHANGED(sampass, element));
1923 }
1924
1925 /**********************************************************************
1926  Add struct samu to LDAP.
1927 *********************************************************************/
1928
1929 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1930 {
1931         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1932         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1933         int rc;
1934         LDAPMessage     *result = NULL;
1935         LDAPMessage     *entry  = NULL;
1936         pstring         dn;
1937         LDAPMod         **mods = NULL;
1938         int             ldap_op = LDAP_MOD_REPLACE;
1939         uint32          num_result;
1940         const char      **attr_list;
1941         char            *escape_user;
1942         const char      *username = pdb_get_username(newpwd);
1943         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
1944         pstring         filter;
1945         fstring         sid_string;
1946
1947         if (!username || !*username) {
1948                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
1949                 return NT_STATUS_INVALID_PARAMETER;
1950         }
1951
1952         /* free this list after the second search or in case we exit on failure */
1953         attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1954
1955         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
1956
1957         if (rc != LDAP_SUCCESS) {
1958                 TALLOC_FREE( attr_list );
1959                 return NT_STATUS_UNSUCCESSFUL;
1960         }
1961
1962         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1963                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
1964                          username));
1965                 ldap_msgfree(result);
1966                 TALLOC_FREE( attr_list );
1967                 return NT_STATUS_UNSUCCESSFUL;
1968         }
1969         ldap_msgfree(result);
1970         result = NULL;
1971
1972         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
1973                 rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1974                                                   sid, &result); 
1975                 if (rc == LDAP_SUCCESS) {
1976                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1977                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' already in the base, with samba attributes\n", 
1978                                          sid_to_string(sid_string, sid)));
1979                                 TALLOC_FREE( attr_list );
1980                                 ldap_msgfree(result);
1981                                 return NT_STATUS_UNSUCCESSFUL;
1982                         }
1983                         ldap_msgfree(result);
1984                 }
1985         }
1986
1987         /* does the entry already exist but without a samba attributes?
1988            we need to return the samba attributes here */
1989            
1990         escape_user = escape_ldap_string_alloc( username );
1991         pstrcpy( filter, "(uid=%u)" );
1992         all_string_sub( filter, "%u", escape_user, sizeof(filter) );
1993         SAFE_FREE( escape_user );
1994
1995         rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1996                                    filter, attr_list, &result);
1997         if ( rc != LDAP_SUCCESS ) {
1998                 TALLOC_FREE( attr_list );
1999                 return NT_STATUS_UNSUCCESSFUL;
2000         }
2001
2002         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2003         
2004         if (num_result > 1) {
2005                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2006                 TALLOC_FREE( attr_list );
2007                 ldap_msgfree(result);
2008                 return NT_STATUS_UNSUCCESSFUL;
2009         }
2010         
2011         /* Check if we need to update an existing entry */
2012         if (num_result == 1) {
2013                 char *tmp;
2014                 
2015                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2016                 ldap_op = LDAP_MOD_REPLACE;
2017                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2018                 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
2019                 if (!tmp) {
2020                         TALLOC_FREE( attr_list );
2021                         ldap_msgfree(result);
2022                         return NT_STATUS_UNSUCCESSFUL;
2023                 }
2024                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
2025                 SAFE_FREE(tmp);
2026
2027         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2028
2029                 /* There might be a SID for this account already - say an idmap entry */
2030
2031                 pstr_sprintf(filter, "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))", 
2032                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
2033                          sid_to_string(sid_string, sid),
2034                          LDAP_OBJ_IDMAP_ENTRY,
2035                          LDAP_OBJ_SID_ENTRY);
2036                 
2037                 /* free old result before doing a new search */
2038                 if (result != NULL) {
2039                         ldap_msgfree(result);
2040                         result = NULL;
2041                 }
2042                 rc = smbldap_search_suffix(ldap_state->smbldap_state, 
2043                                            filter, attr_list, &result);
2044                         
2045                 if ( rc != LDAP_SUCCESS ) {
2046                         TALLOC_FREE( attr_list );
2047                         return NT_STATUS_UNSUCCESSFUL;
2048                 }
2049                 
2050                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2051                 
2052                 if (num_result > 1) {
2053                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2054                         TALLOC_FREE( attr_list );
2055                         ldap_msgfree(result);
2056                         return NT_STATUS_UNSUCCESSFUL;
2057                 }
2058                 
2059                 /* Check if we need to update an existing entry */
2060                 if (num_result == 1) {
2061                         char *tmp;
2062                         
2063                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2064                         ldap_op = LDAP_MOD_REPLACE;
2065                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2066                         tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
2067                         if (!tmp) {
2068                                 TALLOC_FREE( attr_list );
2069                                 ldap_msgfree(result);
2070                                 return NT_STATUS_UNSUCCESSFUL;
2071                         }
2072                         slprintf (dn, sizeof (dn) - 1, "%s", tmp);
2073                         SAFE_FREE(tmp);
2074                 }
2075         }
2076         
2077         TALLOC_FREE( attr_list );
2078
2079         if (num_result == 0) {
2080                 /* Check if we need to add an entry */
2081                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2082                 ldap_op = LDAP_MOD_ADD;
2083                 if (username[strlen(username)-1] == '$') {
2084                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_machine_suffix ());
2085                 } else {
2086                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_user_suffix ());
2087                 }
2088         }
2089
2090         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2091                                 element_is_set_or_changed)) {
2092                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2093                 ldap_msgfree(result);
2094                 if (mods != NULL)
2095                         ldap_mods_free(mods,True);
2096                 return NT_STATUS_UNSUCCESSFUL;          
2097         }
2098         
2099         ldap_msgfree(result);
2100
2101         if (mods == NULL) {
2102                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2103                 return NT_STATUS_UNSUCCESSFUL;
2104         }
2105         switch ( ldap_state->schema_ver ) {
2106                 case SCHEMAVER_SAMBAACCOUNT:
2107                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2108                         break;
2109                 case SCHEMAVER_SAMBASAMACCOUNT:
2110                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2111                         break;
2112                 default:
2113                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2114                         break;
2115         }
2116
2117         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2118         if (!NT_STATUS_IS_OK(ret)) {
2119                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2120                          pdb_get_username(newpwd),dn));
2121                 ldap_mods_free(mods, True);
2122                 return ret;
2123         }
2124
2125         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2126         ldap_mods_free(mods, True);
2127         
2128         return NT_STATUS_OK;
2129 }
2130
2131 /**********************************************************************
2132  *********************************************************************/
2133
2134 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2135                                      const char *filter,
2136                                      LDAPMessage ** result)
2137 {
2138         int scope = LDAP_SCOPE_SUBTREE;
2139         int rc;
2140         const char **attr_list;
2141
2142         attr_list = get_attr_list(NULL, groupmap_attr_list);
2143         rc = smbldap_search(ldap_state->smbldap_state, 
2144                             lp_ldap_group_suffix (), scope,
2145                             filter, attr_list, 0, result);
2146         TALLOC_FREE(attr_list);
2147
2148         return rc;
2149 }
2150
2151 /**********************************************************************
2152  *********************************************************************/
2153
2154 static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
2155                                  GROUP_MAP *map, LDAPMessage *entry)
2156 {
2157         pstring temp;
2158
2159         if (ldap_state == NULL || map == NULL || entry == NULL ||
2160                         ldap_state->smbldap_state->ldap_struct == NULL) {
2161                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2162                 return False;
2163         }
2164
2165         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2166                         get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER), temp)) {
2167                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2168                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2169                 return False;
2170         }
2171         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2172
2173         map->gid = (gid_t)atol(temp);
2174
2175         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2176                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID), temp)) {
2177                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2178                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2179                 return False;
2180         }
2181         
2182         if (!string_to_sid(&map->sid, temp)) {
2183                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2184                 return False;
2185         }
2186
2187         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2188                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), temp)) {
2189                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2190                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2191                 return False;
2192         }
2193         map->sid_name_use = (enum SID_NAME_USE)atol(temp);
2194
2195         if ((map->sid_name_use < SID_NAME_USER) ||
2196                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2197                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2198                 return False;
2199         }
2200
2201         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2202                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), temp)) {
2203                 temp[0] = '\0';
2204                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2205                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_CN), temp)) 
2206                 {
2207                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2208 for gidNumber(%lu)\n",(unsigned long)map->gid));
2209                         return False;
2210                 }
2211         }
2212         fstrcpy(map->nt_name, temp);
2213
2214         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2215                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), temp)) {
2216                 temp[0] = '\0';
2217         }
2218         fstrcpy(map->comment, temp);
2219
2220         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
2221                 store_gid_sid_cache(&map->sid, map->gid);
2222         }
2223
2224         return True;
2225 }
2226
2227 /**********************************************************************
2228  *********************************************************************/
2229
2230 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2231                                  const char *filter,
2232                                  GROUP_MAP *map)
2233 {
2234         struct ldapsam_privates *ldap_state =
2235                 (struct ldapsam_privates *)methods->private_data;
2236         LDAPMessage *result = NULL;
2237         LDAPMessage *entry = NULL;
2238         int count;
2239
2240         if (ldapsam_search_one_group(ldap_state, filter, &result)
2241             != LDAP_SUCCESS) {
2242                 return NT_STATUS_NO_SUCH_GROUP;
2243         }
2244
2245         count = ldap_count_entries(priv2ld(ldap_state), result);
2246
2247         if (count < 1) {
2248                 DEBUG(4, ("ldapsam_getgroup: Did not find group\n"));
2249                 ldap_msgfree(result);
2250                 return NT_STATUS_NO_SUCH_GROUP;
2251         }
2252
2253         if (count > 1) {
2254                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2255                           "count=%d\n", filter, count));
2256                 ldap_msgfree(result);
2257                 return NT_STATUS_NO_SUCH_GROUP;
2258         }
2259
2260         entry = ldap_first_entry(priv2ld(ldap_state), result);
2261
2262         if (!entry) {
2263                 ldap_msgfree(result);
2264                 return NT_STATUS_UNSUCCESSFUL;
2265         }
2266
2267         if (!init_group_from_ldap(ldap_state, map, entry)) {
2268                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2269                           "group filter %s\n", filter));
2270                 ldap_msgfree(result);
2271                 return NT_STATUS_NO_SUCH_GROUP;
2272         }
2273
2274         ldap_msgfree(result);
2275         return NT_STATUS_OK;
2276 }
2277
2278 /**********************************************************************
2279  *********************************************************************/
2280
2281 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2282                                  DOM_SID sid)
2283 {
2284         pstring filter;
2285
2286         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
2287                 LDAP_OBJ_GROUPMAP, 
2288                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2289                 sid_string_static(&sid));
2290
2291         return ldapsam_getgroup(methods, filter, map);
2292 }
2293
2294 /**********************************************************************
2295  *********************************************************************/
2296
2297 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2298                                  gid_t gid)
2299 {
2300         pstring filter;
2301
2302         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))",
2303                 LDAP_OBJ_GROUPMAP,
2304                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2305                 (unsigned long)gid);
2306
2307         return ldapsam_getgroup(methods, filter, map);
2308 }
2309
2310 /**********************************************************************
2311  *********************************************************************/
2312
2313 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2314                                  const char *name)
2315 {
2316         pstring filter;
2317         char *escape_name = escape_ldap_string_alloc(name);
2318
2319         if (!escape_name) {
2320                 return NT_STATUS_NO_MEMORY;
2321         }
2322
2323         pstr_sprintf(filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2324                 LDAP_OBJ_GROUPMAP,
2325                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2326                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN), escape_name);
2327
2328         SAFE_FREE(escape_name);
2329
2330         return ldapsam_getgroup(methods, filter, map);
2331 }
2332
2333 static void add_rid_to_array_unique(TALLOC_CTX *mem_ctx,
2334                                     uint32 rid, uint32 **pp_rids, size_t *p_num)
2335 {
2336         size_t i;
2337
2338         for (i=0; i<*p_num; i++) {
2339                 if ((*pp_rids)[i] == rid)
2340                         return;
2341         }
2342         
2343         *pp_rids = TALLOC_REALLOC_ARRAY(mem_ctx, *pp_rids, uint32, *p_num+1);
2344
2345         if (*pp_rids == NULL)
2346                 return;
2347
2348         (*pp_rids)[*p_num] = rid;
2349         *p_num += 1;
2350 }
2351
2352 static BOOL ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2353                                            LDAPMessage *entry,
2354                                            const DOM_SID *domain_sid,
2355                                            uint32 *rid)
2356 {
2357         fstring str;
2358         DOM_SID sid;
2359
2360         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2361                                           str, sizeof(str)-1)) {
2362                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2363                 return False;
2364         }
2365
2366         if (!string_to_sid(&sid, str)) {
2367                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2368                 return False;
2369         }
2370
2371         if (sid_compare_domain(&sid, domain_sid) != 0) {
2372                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2373                            str, sid_string_static(domain_sid)));
2374                 return False;
2375         }
2376
2377         if (!sid_peek_rid(&sid, rid)) {
2378                 DEBUG(10, ("Could not peek into RID\n"));
2379                 return False;
2380         }
2381
2382         return True;
2383 }
2384
2385 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2386                                            TALLOC_CTX *mem_ctx,
2387                                            const DOM_SID *group,
2388                                            uint32 **pp_member_rids,
2389                                            size_t *p_num_members)
2390 {
2391         struct ldapsam_privates *ldap_state =
2392                 (struct ldapsam_privates *)methods->private_data;
2393         struct smbldap_state *conn = ldap_state->smbldap_state;
2394         pstring filter;
2395         int rc, count;
2396         LDAPMessage *msg = NULL;
2397         LDAPMessage *entry;
2398         char **values = NULL;
2399         char **memberuid;
2400         char *sid_filter = NULL;
2401         char *tmp;
2402         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2403
2404         *pp_member_rids = NULL;
2405         *p_num_members = 0;
2406
2407         pstr_sprintf(filter,
2408                      "(&(objectClass=sambaSamAccount)"
2409                      "(sambaPrimaryGroupSid=%s))",
2410                      sid_string_static(group));
2411
2412         {
2413                 const char *attrs[] = { "sambaSID", NULL };
2414                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2415                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2416                                     &msg);
2417         }
2418
2419         if (rc != LDAP_SUCCESS)
2420                 goto done;
2421
2422         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2423              entry != NULL;
2424              entry = ldap_next_entry(conn->ldap_struct, entry))
2425         {
2426                 uint32 rid;
2427
2428                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2429                                                     entry,
2430                                                     get_global_sam_sid(),
2431                                                     &rid)) {
2432                         DEBUG(2, ("Could not find sid from ldap entry\n"));
2433                         continue;
2434                 }
2435
2436                 add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2437                                         p_num_members);
2438         }
2439
2440         if (msg != NULL)
2441                 ldap_msgfree(msg);
2442
2443         pstr_sprintf(filter,
2444                      "(&(objectClass=sambaGroupMapping)"
2445                      "(objectClass=posixGroup)"
2446                      "(sambaSID=%s))",
2447                      sid_string_static(group));
2448
2449         {
2450                 const char *attrs[] = { "memberUid", NULL };
2451                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2452                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2453                                     &msg);
2454         }
2455
2456         if (rc != LDAP_SUCCESS)
2457                 goto done;
2458
2459         count = ldap_count_entries(conn->ldap_struct, msg);
2460
2461         if (count > 1) {
2462                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2463                           sid_string_static(group)));
2464                 goto done;
2465         }
2466
2467         if (count == 0) {
2468                 result = NT_STATUS_OK;
2469                 goto done;
2470         }
2471
2472         entry = ldap_first_entry(conn->ldap_struct, msg);
2473         if (entry == NULL)
2474                 goto done;
2475
2476         values = ldap_get_values(conn->ldap_struct, msg, "memberUid");
2477         if (values == NULL) {
2478                 result = NT_STATUS_OK;
2479                 goto done;
2480         }
2481
2482         sid_filter = SMB_STRDUP("(&(objectClass=sambaSamAccount)(|");
2483         if (sid_filter == NULL) {
2484                 result = NT_STATUS_NO_MEMORY;
2485                 goto done;
2486         }
2487
2488         for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2489                 tmp = sid_filter;
2490                 asprintf(&sid_filter, "%s(uid=%s)", tmp, *memberuid);
2491                 free(tmp);
2492                 if (sid_filter == NULL) {
2493                         result = NT_STATUS_NO_MEMORY;
2494                         goto done;
2495                 }
2496         }
2497
2498         tmp = sid_filter;
2499         asprintf(&sid_filter, "%s))", sid_filter);
2500         free(tmp);
2501         if (sid_filter == NULL) {
2502                 result = NT_STATUS_NO_MEMORY;
2503                 goto done;
2504         }
2505
2506         {
2507                 const char *attrs[] = { "sambaSID", NULL };
2508                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2509                                     LDAP_SCOPE_SUBTREE, sid_filter, attrs, 0,
2510                                     &msg);
2511         }
2512
2513         if (rc != LDAP_SUCCESS)
2514                 goto done;
2515
2516         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2517              entry != NULL;
2518              entry = ldap_next_entry(conn->ldap_struct, entry))
2519         {
2520                 fstring str;
2521                 DOM_SID sid;
2522                 uint32 rid;
2523
2524                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2525                                                   entry, "sambaSID",
2526                                                   str, sizeof(str)-1))
2527                         continue;
2528
2529                 if (!string_to_sid(&sid, str))
2530                         goto done;
2531
2532                 if (!sid_check_is_in_our_domain(&sid)) {
2533                         DEBUG(1, ("Inconsistent SAM -- group member uid not "
2534                                   "in our domain\n"));
2535                         continue;
2536                 }
2537
2538                 sid_peek_rid(&sid, &rid);
2539
2540                 add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2541                                         p_num_members);
2542         }
2543
2544         result = NT_STATUS_OK;
2545         
2546  done:
2547         SAFE_FREE(sid_filter);
2548
2549         if (values != NULL)
2550                 ldap_value_free(values);
2551
2552         if (msg != NULL)
2553                 ldap_msgfree(msg);
2554
2555         return result;
2556 }
2557
2558 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2559                                                TALLOC_CTX *mem_ctx,
2560                                                struct samu *user,
2561                                                DOM_SID **pp_sids,
2562                                                gid_t **pp_gids,
2563                                                size_t *p_num_groups)
2564 {
2565         struct ldapsam_privates *ldap_state =
2566                 (struct ldapsam_privates *)methods->private_data;
2567         struct smbldap_state *conn = ldap_state->smbldap_state;
2568         pstring filter;
2569         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2570         char *escape_name;
2571         int rc;
2572         LDAPMessage *msg = NULL;
2573         LDAPMessage *entry;
2574         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2575         size_t num_sids, num_gids;
2576         gid_t primary_gid;
2577
2578         *pp_sids = NULL;
2579         num_sids = 0;
2580
2581         if (!sid_to_gid(pdb_get_group_sid(user), &primary_gid)) {
2582                 DEBUG(1, ("sid_to_gid failed for user's primary group\n"));
2583                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2584         }
2585
2586         escape_name = escape_ldap_string_alloc(pdb_get_username(user));
2587
2588         if (escape_name == NULL)
2589                 return NT_STATUS_NO_MEMORY;
2590
2591         pstr_sprintf(filter, "(&(objectClass=posixGroup)"
2592                      "(|(memberUid=%s)(gidNumber=%d)))",
2593                      escape_name, primary_gid);
2594
2595         rc = smbldap_search(conn, lp_ldap_group_suffix(),
2596                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &msg);
2597
2598         if (rc != LDAP_SUCCESS)
2599                 goto done;
2600
2601         num_gids = 0;
2602         *pp_gids = NULL;
2603
2604         num_sids = 0;
2605         *pp_sids = NULL;
2606
2607         /* We need to add the primary group as the first gid/sid */
2608
2609         add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids);
2610
2611         /* This sid will be replaced later */
2612
2613         add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids, &num_sids);
2614
2615         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2616              entry != NULL;
2617              entry = ldap_next_entry(conn->ldap_struct, entry))
2618         {
2619                 fstring str;
2620                 DOM_SID sid;
2621                 gid_t gid;
2622                 char *end;
2623
2624                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2625                                                   entry, "sambaSID",
2626                                                   str, sizeof(str)-1))
2627                         continue;
2628
2629                 if (!string_to_sid(&sid, str))
2630                         goto done;
2631
2632                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2633                                                   entry, "gidNumber",
2634                                                   str, sizeof(str)-1))
2635                         continue;
2636
2637                 gid = strtoul(str, &end, 10);
2638
2639                 if (PTR_DIFF(end, str) != strlen(str))
2640                         goto done;
2641
2642                 if (gid == primary_gid) {
2643                         sid_copy(&(*pp_sids)[0], &sid);
2644                 } else {
2645                         add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2646                                                 &num_gids);
2647                         add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2648                                                 &num_sids);
2649                 }
2650         }
2651
2652         if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2653                 DEBUG(3, ("primary group of [%s] not found\n",
2654                           pdb_get_username(user)));
2655                 goto done;
2656         }
2657
2658         *p_num_groups = num_sids;
2659
2660         result = NT_STATUS_OK;
2661
2662  done:
2663
2664         SAFE_FREE(escape_name);
2665         if (msg != NULL)
2666                 ldap_msgfree(msg);
2667
2668         return result;
2669 }
2670
2671 /**********************************************************************
2672  * Augment a posixGroup object with a sambaGroupMapping domgroup
2673  *********************************************************************/
2674
2675 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2676                                        struct ldapsam_privates *ldap_state,
2677                                        GROUP_MAP *map)
2678 {
2679         const char *filter, *dn;
2680         LDAPMessage *msg, *entry;
2681         LDAPMod **mods;
2682         int rc;
2683
2684         filter = talloc_asprintf(mem_ctx,
2685                                  "(&(objectClass=posixGroup)(gidNumber=%u))",
2686                                  map->gid);
2687         if (filter == NULL) {
2688                 return NT_STATUS_NO_MEMORY;
2689         }
2690
2691         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2692                                    get_attr_list(mem_ctx, groupmap_attr_list),
2693                                    &msg);
2694         talloc_autofree_ldapmsg(mem_ctx, msg);
2695
2696         if ((rc != LDAP_SUCCESS) ||
2697             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2698             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2699                 return NT_STATUS_NO_SUCH_GROUP;
2700         }
2701
2702         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2703         if (dn == NULL) {
2704                 return NT_STATUS_NO_MEMORY;
2705         }
2706
2707         mods = NULL;
2708         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
2709                         "sambaGroupMapping");
2710         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
2711                          sid_string_static(&map->sid));
2712         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
2713                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2714         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2715                          map->nt_name);
2716         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2717                          map->comment);
2718         talloc_autofree_ldapmod(mem_ctx, mods);
2719
2720         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2721         if (rc != LDAP_SUCCESS) {
2722                 return NT_STATUS_ACCESS_DENIED;
2723         }
2724
2725         return NT_STATUS_OK;
2726 }
2727
2728 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
2729                                                 GROUP_MAP *map)
2730 {
2731         struct ldapsam_privates *ldap_state =
2732                 (struct ldapsam_privates *)methods->private_data;
2733         LDAPMessage *msg = NULL;
2734         LDAPMod **mods = NULL;
2735         const char *attrs[] = { NULL };
2736         char *filter;
2737
2738         char *dn;
2739         TALLOC_CTX *mem_ctx;
2740         NTSTATUS result;
2741
2742         DOM_SID sid;
2743
2744         int rc;
2745
2746         mem_ctx = talloc_new(NULL);
2747         if (mem_ctx == NULL) {
2748                 DEBUG(0, ("talloc_new failed\n"));
2749                 return NT_STATUS_NO_MEMORY;
2750         }
2751
2752         filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
2753                                  sid_string_static(&map->sid));
2754         if (filter == NULL) {
2755                 result = NT_STATUS_NO_MEMORY;
2756                 goto done;
2757         }
2758
2759         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
2760                             LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
2761         talloc_autofree_ldapmsg(mem_ctx, msg);
2762
2763         if ((rc == LDAP_SUCCESS) &&
2764             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
2765
2766                 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
2767                           "group mapping entry\n",
2768                           sid_string_static(&map->sid)));
2769                 result = NT_STATUS_GROUP_EXISTS;
2770                 goto done;
2771         }
2772
2773         switch (map->sid_name_use) {
2774
2775         case SID_NAME_DOM_GRP:
2776                 /* To map a domain group we need to have a posix group
2777                    to attach to. */
2778                 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
2779                 goto done;
2780                 break;
2781
2782         case SID_NAME_ALIAS:
2783                 if (!sid_check_is_in_our_domain(&map->sid)) {
2784                         DEBUG(3, ("Refusing to map sid %s as an alias, not "
2785                                   "in our domain\n",
2786                                   sid_string_static(&map->sid)));
2787                         result = NT_STATUS_INVALID_PARAMETER;
2788                         goto done;
2789                 }
2790                 break;
2791
2792         case SID_NAME_WKN_GRP:
2793                 if (!sid_check_is_in_builtin(&map->sid)) {
2794                         DEBUG(3, ("Refusing to map sid %s as an alias, not "
2795                                   "in builtin domain\n",
2796                                   sid_string_static(&map->sid)));
2797                         result = NT_STATUS_INVALID_PARAMETER;
2798                         goto done;
2799                 }
2800                 break;
2801
2802         default:
2803                 DEBUG(3, ("Got invalid use '%s' for mapping\n",
2804                           sid_type_lookup(map->sid_name_use)));
2805                 result = NT_STATUS_INVALID_PARAMETER;
2806                 goto done;
2807         }
2808
2809         /* Domain groups have been mapped in a separate routine, we have to
2810          * create an alias now */
2811
2812         if (map->gid == -1) {
2813                 DEBUG(10, ("Refusing to map gid==-1\n"));
2814                 result = NT_STATUS_INVALID_PARAMETER;
2815                 goto done;
2816         }
2817
2818         if (pdb_gid_to_sid(map->gid, &sid)) {
2819                 DEBUG(3, ("Gid %d is already mapped to SID %s, refusing to "
2820                           "add\n", map->gid, sid_string_static(&sid)));
2821                 result = NT_STATUS_GROUP_EXISTS;
2822                 goto done;
2823         }
2824
2825         /* Ok, enough checks done. It's still racy to go ahead now, but that's
2826          * the best we can get out of LDAP. */
2827
2828         dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
2829                              sid_string_static(&map->sid),
2830                              lp_ldap_group_suffix());
2831         if (dn == NULL) {
2832                 result = NT_STATUS_NO_MEMORY;
2833                 goto done;
2834         }
2835
2836         mods = NULL;
2837
2838         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
2839                          "sambaSidEntry");
2840         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
2841                          "sambaGroupMapping");
2842
2843         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
2844                          sid_string_static(&map->sid));
2845         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
2846                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2847         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
2848                          map->nt_name);
2849         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
2850                          map->comment);
2851         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
2852                          talloc_asprintf(mem_ctx, "%u", map->gid));
2853         talloc_autofree_ldapmod(mem_ctx, mods);
2854
2855         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
2856
2857         result = (rc == LDAP_SUCCESS) ?
2858                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
2859
2860  done:
2861         TALLOC_FREE(mem_ctx);
2862         return result;
2863 }
2864
2865 /**********************************************************************
2866  * Update a group mapping entry. We're quite strict about what can be changed:
2867  * Only the description and displayname may be changed. It simply does not
2868  * make any sense to change the SID, gid or the type in a mapping.
2869  *********************************************************************/
2870
2871 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
2872                                                    GROUP_MAP *map)
2873 {
2874         struct ldapsam_privates *ldap_state =
2875                 (struct ldapsam_privates *)methods->private_data;
2876         int rc;
2877         const char *filter, *dn;
2878         LDAPMessage *msg = NULL;
2879         LDAPMessage *entry = NULL;
2880         LDAPMod **mods = NULL;
2881         TALLOC_CTX *mem_ctx;
2882         NTSTATUS result;
2883
2884         mem_ctx = talloc_new(NULL);
2885         if (mem_ctx == NULL) {
2886                 DEBUG(0, ("talloc_new failed\n"));
2887                 return NT_STATUS_NO_MEMORY;
2888         }
2889
2890         /* Make 100% sure that sid, gid and type are not changed by looking up
2891          * exactly the values we're given in LDAP. */
2892
2893         filter = talloc_asprintf(mem_ctx, "(&(objectClass=sambaGroupMapping)"
2894                                  "(sambaSid=%s)(gidNumber=%u)"
2895                                  "(sambaGroupType=%d))",
2896                                  sid_string_static(&map->sid), map->gid,
2897                                  map->sid_name_use);
2898         if (filter == NULL) {
2899                 result = NT_STATUS_NO_MEMORY;
2900                 goto done;
2901         }
2902
2903         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2904                                    get_attr_list(mem_ctx, groupmap_attr_list),
2905                                    &msg);
2906         talloc_autofree_ldapmsg(mem_ctx, msg);
2907
2908         if ((rc != LDAP_SUCCESS) ||
2909             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2910             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2911                 result = NT_STATUS_NO_SUCH_GROUP;
2912                 goto done;
2913         }
2914
2915         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2916
2917         if (dn == NULL) {
2918                 result = NT_STATUS_NO_MEMORY;
2919                 goto done;
2920         }
2921
2922         mods = NULL;
2923         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2924                          map->nt_name);
2925         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2926                          map->comment);
2927         talloc_autofree_ldapmod(mem_ctx, mods);
2928
2929         if (mods == NULL) {
2930                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
2931                           "nothing to do\n"));
2932                 result = NT_STATUS_OK;
2933                 goto done;
2934         }
2935
2936         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2937
2938         if (rc != LDAP_SUCCESS) {
2939                 result = NT_STATUS_ACCESS_DENIED;
2940                 goto done;
2941         }
2942
2943         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
2944                   "group %lu in LDAP\n", (unsigned long)map->gid));
2945
2946         result = NT_STATUS_OK;
2947
2948  done:
2949         TALLOC_FREE(mem_ctx);
2950         return result;
2951 }
2952
2953 /**********************************************************************
2954  *********************************************************************/
2955
2956 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
2957                                                    DOM_SID sid)
2958 {
2959         struct ldapsam_privates *priv =
2960                 (struct ldapsam_privates *)methods->private_data;
2961         LDAPMessage *msg, *entry;
2962         int rc;
2963         NTSTATUS result;
2964         TALLOC_CTX *mem_ctx;
2965         char *filter;
2966
2967         mem_ctx = talloc_new(NULL);
2968         if (mem_ctx == NULL) {
2969                 DEBUG(0, ("talloc_new failed\n"));
2970                 return NT_STATUS_NO_MEMORY;
2971         }
2972
2973         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
2974                                  LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
2975                                  sid_string_static(&sid));
2976         if (filter == NULL) {
2977                 result = NT_STATUS_NO_MEMORY;
2978                 goto done;
2979         }
2980         rc = smbldap_search_suffix(priv->smbldap_state, filter,
2981                                    get_attr_list(mem_ctx, groupmap_attr_list),
2982                                    &msg);
2983         talloc_autofree_ldapmsg(mem_ctx, msg);
2984
2985         if ((rc != LDAP_SUCCESS) ||
2986             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
2987             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
2988                 result = NT_STATUS_NO_SUCH_GROUP;
2989                 goto done;
2990         }
2991
2992         rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
2993                                   get_attr_list(mem_ctx,
2994                                                 groupmap_attr_list_to_delete));
2995  
2996         if ((rc == LDAP_NAMING_VIOLATION) ||
2997             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
2998                 const char *attrs[] = { "sambaGroupType", "description",
2999                                         "displayName", "sambaSIDList",
3000                                         NULL };
3001
3002                 /* Second try. Don't delete the sambaSID attribute, this is
3003                    for "old" entries that are tacked on a winbind
3004                    sambaIdmapEntry. */
3005
3006                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3007                                           LDAP_OBJ_GROUPMAP, attrs);
3008         }
3009
3010         if ((rc == LDAP_NAMING_VIOLATION) ||
3011             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3012                 const char *attrs[] = { "sambaGroupType", "description",
3013                                         "displayName", "sambaSIDList",
3014                                         "gidNumber", NULL };
3015
3016                 /* Third try. This is a post-3.0.21 alias (containing only
3017                  * sambaSidEntry and sambaGroupMapping classes), we also have
3018                  * to delete the gidNumber attribute, only the sambaSidEntry
3019                  * remains */
3020
3021                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3022                                           LDAP_OBJ_GROUPMAP, attrs);
3023         }
3024
3025         result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3026
3027  done:
3028         TALLOC_FREE(mem_ctx);
3029         return result;
3030  }
3031
3032 /**********************************************************************
3033  *********************************************************************/
3034
3035 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3036                                     BOOL update)
3037 {
3038         struct ldapsam_privates *ldap_state =
3039                 (struct ldapsam_privates *)my_methods->private_data;
3040         fstring filter;
3041         int rc;
3042         const char **attr_list;
3043
3044         pstr_sprintf( filter, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3045         attr_list = get_attr_list( NULL, groupmap_attr_list );
3046         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3047                             LDAP_SCOPE_SUBTREE, filter,
3048                             attr_list, 0, &ldap_state->result);
3049         TALLOC_FREE(attr_list);
3050
3051         if (rc != LDAP_SUCCESS) {
3052                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3053                           ldap_err2string(rc)));
3054                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3055                           lp_ldap_group_suffix(), filter));
3056                 ldap_msgfree(ldap_state->result);
3057                 ldap_state->result = NULL;
3058                 return NT_STATUS_UNSUCCESSFUL;
3059         }
3060
3061         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3062                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3063                                      ldap_state->result)));
3064
3065         ldap_state->entry =
3066                 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3067                                  ldap_state->result);
3068         ldap_state->index = 0;
3069
3070         return NT_STATUS_OK;
3071 }
3072
3073 /**********************************************************************
3074  *********************************************************************/
3075
3076 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3077 {
3078         ldapsam_endsampwent(my_methods);
3079 }
3080
3081 /**********************************************************************
3082  *********************************************************************/
3083
3084 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3085                                     GROUP_MAP *map)
3086 {
3087         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3088         struct ldapsam_privates *ldap_state =
3089                 (struct ldapsam_privates *)my_methods->private_data;
3090         BOOL bret = False;
3091
3092         while (!bret) {
3093                 if (!ldap_state->entry)
3094                         return ret;
3095                 
3096                 ldap_state->index++;
3097                 bret = init_group_from_ldap(ldap_state, map,
3098                                             ldap_state->entry);
3099                 
3100                 ldap_state->entry =
3101                         ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3102                                         ldap_state->entry);     
3103         }
3104
3105         return NT_STATUS_OK;
3106 }
3107
3108 /**********************************************************************
3109  *********************************************************************/
3110
3111 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3112                                            enum SID_NAME_USE sid_name_use,
3113                                            GROUP_MAP **pp_rmap,
3114                                            size_t *p_num_entries,
3115                                            BOOL unix_only)
3116 {
3117         GROUP_MAP map;
3118         GROUP_MAP *mapt;
3119         size_t entries = 0;
3120
3121         *p_num_entries = 0;
3122         *pp_rmap = NULL;
3123
3124         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3125                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3126                           "passdb\n"));
3127                 return NT_STATUS_ACCESS_DENIED;
3128         }
3129
3130         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3131                 if (sid_name_use != SID_NAME_UNKNOWN &&
3132                     sid_name_use != map.sid_name_use) {
3133                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3134                                   "not of the requested type\n", map.nt_name));
3135                         continue;
3136                 }
3137                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3138                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3139                                   "non mapped\n", map.nt_name));
3140                         continue;
3141                 }
3142
3143                 mapt=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3144                 if (!mapt) {
3145                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3146                                  "enlarge group map!\n"));
3147                         SAFE_FREE(*pp_rmap);
3148                         return NT_STATUS_UNSUCCESSFUL;
3149                 }
3150                 else
3151                         (*pp_rmap) = mapt;
3152
3153                 mapt[entries] = map;
3154
3155                 entries += 1;
3156
3157         }
3158         ldapsam_endsamgrent(methods);
3159
3160         *p_num_entries = entries;
3161
3162         return NT_STATUS_OK;
3163 }
3164
3165 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3166                                         const DOM_SID *alias,
3167                                         const DOM_SID *member,
3168                                         int modop)
3169 {
3170         struct ldapsam_privates *ldap_state =
3171                 (struct ldapsam_privates *)methods->private_data;
3172         char *dn;
3173         LDAPMessage *result = NULL;
3174         LDAPMessage *entry = NULL;
3175         int count;
3176         LDAPMod **mods = NULL;
3177         int rc;
3178         enum SID_NAME_USE type = SID_NAME_USE_NONE;
3179
3180         pstring filter;
3181
3182         if (sid_check_is_in_builtin(alias)) {
3183                 type = SID_NAME_WKN_GRP;
3184         }
3185
3186         if (sid_check_is_in_our_domain(alias)) {
3187                 type = SID_NAME_ALIAS;
3188         }
3189
3190         if (type == SID_NAME_USE_NONE) {
3191                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3192                           sid_string_static(alias)));
3193                 return NT_STATUS_NO_SUCH_ALIAS;
3194         }
3195
3196         pstr_sprintf(filter,
3197                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3198                      LDAP_OBJ_GROUPMAP, sid_string_static(alias),
3199                      type);
3200
3201         if (ldapsam_search_one_group(ldap_state, filter,
3202                                      &result) != LDAP_SUCCESS)
3203                 return NT_STATUS_NO_SUCH_ALIAS;
3204
3205         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3206                                    result);
3207
3208         if (count < 1) {
3209                 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3210                 ldap_msgfree(result);
3211                 return NT_STATUS_NO_SUCH_ALIAS;
3212         }
3213
3214         if (count > 1) {
3215                 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3216                           "filter %s: count=%d\n", filter, count));
3217                 ldap_msgfree(result);
3218                 return NT_STATUS_NO_SUCH_ALIAS;
3219         }
3220
3221         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3222                                  result);
3223
3224         if (!entry) {
3225                 ldap_msgfree(result);
3226                 return NT_STATUS_UNSUCCESSFUL;
3227         }
3228
3229         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
3230         if (!dn) {
3231                 ldap_msgfree(result);
3232                 return NT_STATUS_UNSUCCESSFUL;
3233         }
3234
3235         smbldap_set_mod(&mods, modop,
3236                         get_attr_key2string(groupmap_attr_list,
3237                                             LDAP_ATTR_SID_LIST),
3238                         sid_string_static(member));
3239
3240         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3241
3242         ldap_mods_free(mods, True);
3243         ldap_msgfree(result);
3244         SAFE_FREE(dn);
3245
3246         if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3247                 return NT_STATUS_MEMBER_IN_ALIAS;
3248         }
3249
3250         if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3251                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3252         }
3253
3254         if (rc != LDAP_SUCCESS) {
3255                 return NT_STATUS_UNSUCCESSFUL;
3256         }
3257
3258         return NT_STATUS_OK;
3259 }
3260
3261 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3262                                      const DOM_SID *alias,
3263                                      const DOM_SID *member)
3264 {
3265         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3266 }
3267
3268 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3269                                      const DOM_SID *alias,
3270                                      const DOM_SID *member)
3271 {
3272         return ldapsam_modify_aliasmem(methods, alias, member,
3273                                        LDAP_MOD_DELETE);
3274 }
3275
3276 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3277                                       const DOM_SID *alias,
3278                                       DOM_SID **pp_members,
3279                                       size_t *p_num_members)
3280 {
3281         struct ldapsam_privates *ldap_state =
3282                 (struct ldapsam_privates *)methods->private_data;
3283         LDAPMessage *result = NULL;
3284         LDAPMessage *entry = NULL;
3285         int count;
3286         char **values;
3287         int i;
3288         pstring filter;
3289         size_t num_members = 0;
3290         enum SID_NAME_USE type = SID_NAME_USE_NONE;
3291
3292         *pp_members = NULL;
3293         *p_num_members = 0;
3294
3295         if (sid_check_is_in_builtin(alias)) {
3296                 type = SID_NAME_WKN_GRP;
3297         }
3298
3299         if (sid_check_is_in_our_domain(alias)) {
3300                 type = SID_NAME_ALIAS;
3301         }
3302
3303         if (type == SID_NAME_USE_NONE) {
3304                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3305                           sid_string_static(alias)));
3306                 return NT_STATUS_NO_SUCH_ALIAS;
3307         }
3308
3309         pstr_sprintf(filter,
3310                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3311                      LDAP_OBJ_GROUPMAP, sid_string_static(alias),
3312                      type);
3313
3314         if (ldapsam_search_one_group(ldap_state, filter,
3315                                      &result) != LDAP_SUCCESS)
3316                 return NT_STATUS_NO_SUCH_ALIAS;
3317
3318         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3319                                    result);
3320
3321         if (count < 1) {
3322                 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3323                 ldap_msgfree(result);
3324                 return NT_STATUS_NO_SUCH_ALIAS;
3325         }
3326
3327         if (count > 1) {
3328                 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3329                           "filter %s: count=%d\n", filter, count));
3330                 ldap_msgfree(result);
3331                 return NT_STATUS_NO_SUCH_ALIAS;
3332         }
3333
3334         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3335                                  result);
3336
3337         if (!entry) {
3338                 ldap_msgfree(result);
3339                 return NT_STATUS_UNSUCCESSFUL;
3340         }
3341
3342         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3343                                  entry,
3344                                  get_attr_key2string(groupmap_attr_list,
3345                                                      LDAP_ATTR_SID_LIST));
3346
3347         if (values == NULL) {
3348                 ldap_msgfree(result);
3349                 return NT_STATUS_OK;
3350         }
3351
3352         count = ldap_count_values(values);
3353
3354         for (i=0; i<count; i++) {
3355                 DOM_SID member;
3356
3357                 if (!string_to_sid(&member, values[i]))
3358                         continue;
3359
3360                 add_sid_to_array(NULL, &member, pp_members, &num_members);
3361         }
3362
3363         *p_num_members = num_members;
3364         ldap_value_free(values);
3365         ldap_msgfree(result);
3366
3367         return NT_STATUS_OK;
3368 }
3369
3370 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3371                                           TALLOC_CTX *mem_ctx,
3372                                           const DOM_SID *domain_sid,
3373                                           const DOM_SID *members,
3374                                           size_t num_members,
3375                                           uint32 **pp_alias_rids,
3376                                           size_t *p_num_alias_rids)
3377 {
3378         struct ldapsam_privates *ldap_state =
3379                 (struct ldapsam_privates *)methods->private_data;
3380         LDAP *ldap_struct;
3381
3382         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3383
3384         LDAPMessage *result = NULL;
3385         LDAPMessage *entry = NULL;
3386         int i;
3387         int rc;
3388         char *filter;
3389         enum SID_NAME_USE type = SID_NAME_USE_NONE;
3390
3391         if (sid_check_is_builtin(domain_sid)) {
3392                 type = SID_NAME_WKN_GRP;
3393         }
3394
3395         if (sid_check_is_domain(domain_sid)) {
3396                 type = SID_NAME_ALIAS;
3397         }
3398
3399         if (type == SID_NAME_USE_NONE) {
3400                 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3401                           sid_string_static(domain_sid)));
3402                 return NT_STATUS_UNSUCCESSFUL;
3403         }
3404
3405         filter = talloc_asprintf(mem_ctx,
3406                                  "(&(|(objectclass=%s)(sambaGroupType=%d))(|",
3407                                  LDAP_OBJ_GROUPMAP, type);
3408
3409         for (i=0; i<num_members; i++)
3410                 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3411                                          filter,
3412                                          sid_string_static(&members[i]));
3413
3414         filter = talloc_asprintf(mem_ctx, "%s))", filter);
3415
3416         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3417                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3418
3419         if (rc != LDAP_SUCCESS)
3420                 return NT_STATUS_UNSUCCESSFUL;
3421
3422         ldap_struct = ldap_state->smbldap_state->ldap_struct;
3423
3424         for (entry = ldap_first_entry(ldap_struct, result);
3425              entry != NULL;
3426              entry = ldap_next_entry(ldap_struct, entry))
3427         {
3428                 fstring sid_str;
3429                 DOM_SID sid;
3430                 uint32 rid;
3431
3432                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3433                                                   LDAP_ATTRIBUTE_SID,
3434                                                   sid_str,
3435                                                   sizeof(sid_str)-1))
3436                         continue;
3437
3438                 if (!string_to_sid(&sid, sid_str))
3439                         continue;
3440
3441                 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3442                         continue;
3443
3444                 add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3445                                         p_num_alias_rids);
3446         }
3447
3448         ldap_msgfree(result);
3449         return NT_STATUS_OK;
3450 }
3451
3452 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3453                                                    int policy_index,
3454                                                    uint32 value)
3455 {
3456         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3457         int rc;
3458         LDAPMod **mods = NULL;
3459         fstring value_string;
3460         const char *policy_attr = NULL;
3461
3462         struct ldapsam_privates *ldap_state =
3463                 (struct ldapsam_privates *)methods->private_data;
3464
3465         const char *attrs[2];
3466
3467         DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3468
3469         if (!ldap_state->domain_dn) {
3470                 return NT_STATUS_INVALID_PARAMETER;
3471         }
3472
3473         policy_attr = get_account_policy_attr(policy_index);
3474         if (policy_attr == NULL) {
3475                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3476                          "policy\n"));
3477                 return ntstatus;
3478         }
3479
3480         attrs[0] = policy_attr;
3481         attrs[1] = NULL;
3482
3483         slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3484
3485         smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3486
3487         rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3488                             mods);
3489
3490         ldap_mods_free(mods, True);
3491
3492         if (rc != LDAP_SUCCESS) {
3493                 return ntstatus;
3494         }
3495
3496         if (!cache_account_policy_set(policy_index, value)) {
3497                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3498                          "update local tdb cache\n"));
3499                 return ntstatus;
3500         }
3501
3502         return NT_STATUS_OK;
3503 }
3504
3505 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3506                                            int policy_index, uint32 value)
3507 {
3508         if (!account_policy_migrated(False)) {
3509                 return (account_policy_set(policy_index, value)) ?
3510                         NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3511         }
3512
3513         return ldapsam_set_account_policy_in_ldap(methods, policy_index,
3514                                                   value);
3515 }
3516
3517 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3518                                                      int policy_index,
3519                                                      uint32 *value)
3520 {
3521         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3522         LDAPMessage *result = NULL;
3523         LDAPMessage *entry = NULL;
3524         int count;
3525         int rc;
3526         char **vals = NULL;
3527         const char *policy_attr = NULL;
3528
3529         struct ldapsam_privates *ldap_state =
3530                 (struct ldapsam_privates *)methods->private_data;
3531
3532         const char *attrs[2];
3533
3534         DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3535
3536         if (!ldap_state->domain_dn) {
3537                 return NT_STATUS_INVALID_PARAMETER;
3538         }
3539
3540         policy_attr = get_account_policy_attr(policy_index);
3541         if (!policy_attr) {
3542                 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3543                          "policy index: %d\n", policy_index));
3544                 return ntstatus;
3545         }
3546
3547         attrs[0] = policy_attr;
3548         attrs[1] = NULL;
3549
3550         rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3551                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0,
3552                             &result);
3553
3554         if (rc != LDAP_SUCCESS) {
3555                 return ntstatus;
3556         }
3557
3558         count = ldap_count_entries(priv2ld(ldap_state), result);
3559         if (count < 1) {
3560                 goto out;
3561         }
3562
3563         entry = ldap_first_entry(priv2ld(ldap_state), result);
3564         if (entry == NULL) {
3565                 goto out;
3566         }
3567
3568         vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3569         if (vals == NULL) {
3570                 goto out;
3571         }
3572
3573         *value = (uint32)atol(vals[0]);
3574         
3575         ntstatus = NT_STATUS_OK;
3576
3577 out:
3578         if (vals)
3579                 ldap_value_free(vals);
3580         ldap_msgfree(result);
3581
3582         return ntstatus;
3583 }
3584
3585 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache 
3586
3587    - if user hasn't decided to use account policies inside LDAP just reuse the
3588      old tdb values
3589    
3590    - if there is a valid cache entry, return that
3591    - if there is an LDAP entry, update cache and return 
3592    - otherwise set to default, update cache and return
3593
3594    Guenther
3595 */
3596 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3597                                            int policy_index, uint32 *value)
3598 {
3599         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3600
3601         if (!account_policy_migrated(False)) {
3602                 return (account_policy_get(policy_index, value))
3603                         ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3604         }
3605
3606         if (cache_account_policy_get(policy_index, value)) {
3607                 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3608                           "cache\n"));
3609                 return NT_STATUS_OK;
3610         }
3611
3612         ntstatus = ldapsam_get_account_policy_from_ldap(methods, policy_index,
3613                                                         value);
3614         if (NT_STATUS_IS_OK(ntstatus)) {
3615                 goto update_cache;
3616         }
3617
3618         DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3619                   "ldap\n"));
3620
3621 #if 0
3622         /* should we automagically migrate old tdb value here ? */
3623         if (account_policy_get(policy_index, value))
3624                 goto update_ldap;
3625
3626         DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3627                   "default\n", policy_index));
3628 #endif
3629
3630         if (!account_policy_get_default(policy_index, value)) {
3631                 return ntstatus;
3632         }
3633         
3634 /* update_ldap: */
3635  
3636         ntstatus = ldapsam_set_account_policy(methods, policy_index, *value);
3637         if (!NT_STATUS_IS_OK(ntstatus)) {
3638                 return ntstatus;
3639         }
3640                 
3641  update_cache:
3642  
3643         if (!cache_account_policy_set(policy_index, *value)) {
3644                 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3645                          "tdb as a cache\n"));
3646                 return NT_STATUS_UNSUCCESSFUL;
3647         }
3648
3649         return NT_STATUS_OK;
3650 }
3651
3652 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3653                                     const DOM_SID *domain_sid,
3654                                     int num_rids,
3655                                     uint32 *rids,
3656                                     const char **names,
3657                                     uint32 *attrs)
3658 {
3659         struct ldapsam_privates *ldap_state =
3660                 (struct ldapsam_privates *)methods->private_data;
3661         LDAPMessage *msg = NULL;
3662         LDAPMessage *entry;
3663         char *allsids = NULL;
3664         int i, rc, num_mapped;
3665         NTSTATUS result = NT_STATUS_NO_MEMORY;
3666         TALLOC_CTX *mem_ctx;
3667         LDAP *ld;
3668         BOOL is_builtin;
3669
3670         mem_ctx = talloc_new(NULL);
3671         if (mem_ctx == NULL) {
3672                 DEBUG(0, ("talloc_new failed\n"));
3673                 goto done;
3674         }
3675
3676         if (!sid_check_is_builtin(domain_sid) &&
3677             !sid_check_is_domain(domain_sid)) {
3678                 result = NT_STATUS_INVALID_PARAMETER;
3679                 goto done;
3680         }
3681
3682         for (i=0; i<num_rids; i++)
3683                 attrs[i] = SID_NAME_UNKNOWN;
3684
3685         allsids = talloc_strdup(mem_ctx, "");
3686         if (allsids == NULL) {
3687                 goto done;
3688         }
3689
3690         for (i=0; i<num_rids; i++) {
3691                 DOM_SID sid;
3692                 sid_copy(&sid, domain_sid);
3693                 sid_append_rid(&sid, rids[i]);
3694                 allsids = talloc_asprintf_append(allsids, "(sambaSid=%s)",
3695                                                  sid_string_static(&sid));
3696                 if (allsids == NULL) {
3697                         goto done;
3698                 }
3699         }
3700
3701         /* First look for users */
3702
3703         {
3704                 char *filter;
3705                 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
3706
3707                 filter = talloc_asprintf(
3708                         mem_ctx, ("(&(objectClass=sambaSamAccount)(|%s))"),
3709                         allsids);
3710
3711                 if (filter == NULL) {
3712                         goto done;
3713                 }
3714
3715                 rc = smbldap_search(ldap_state->smbldap_state,
3716                                     lp_ldap_user_suffix(),
3717                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3718                                     &msg);
3719                 talloc_autofree_ldapmsg(mem_ctx, msg);
3720         }
3721
3722         if (rc != LDAP_SUCCESS)
3723                 goto done;
3724
3725         ld = ldap_state->smbldap_state->ldap_struct;
3726         num_mapped = 0;
3727
3728         for (entry = ldap_first_entry(ld, msg);
3729              entry != NULL;
3730              entry = ldap_next_entry(ld, entry)) {
3731                 uint32 rid;
3732                 int rid_index;
3733                 const char *name;
3734
3735                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
3736                                                     &rid)) {
3737                         DEBUG(2, ("Could not find sid from ldap entry\n"));
3738                         continue;
3739                 }
3740
3741                 name = smbldap_talloc_single_attribute(ld, entry, "uid",
3742                                                        names);
3743                 if (name == NULL) {
3744                         DEBUG(2, ("Could not retrieve uid attribute\n"));
3745                         continue;
3746                 }
3747
3748                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3749                         if (rid == rids[rid_index])
3750                                 break;
3751                 }
3752
3753                 if (rid_index == num_rids) {
3754                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3755                         continue;
3756                 }
3757
3758                 attrs[rid_index] = SID_NAME_USER;
3759                 names[rid_index] = name;
3760                 num_mapped += 1;
3761         }
3762
3763         if (num_mapped == num_rids) {
3764                 /* No need to look for groups anymore -- we're done */
3765                 result = NT_STATUS_OK;
3766                 goto done;
3767         }
3768
3769         /* Same game for groups */
3770
3771         {
3772                 char *filter;
3773                 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
3774                                              "sambaGroupType", NULL };
3775
3776                 filter = talloc_asprintf(
3777                         mem_ctx, "(&(objectClass=sambaGroupMapping)(|%s))",
3778                         allsids);
3779                 if (filter == NULL) {
3780                         goto done;
3781                 }
3782
3783                 rc = smbldap_search(ldap_state->smbldap_state,
3784                                     lp_ldap_group_suffix(),
3785                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3786                                     &msg);
3787                 talloc_autofree_ldapmsg(mem_ctx, msg);
3788         }
3789
3790         if (rc != LDAP_SUCCESS)
3791                 goto done;
3792
3793         /* ldap_struct might have changed due to a reconnect */
3794
3795         ld = ldap_state->smbldap_state->ldap_struct;
3796
3797         /* For consistency checks, we already checked we're only domain or builtin */
3798
3799         is_builtin = sid_check_is_builtin(domain_sid);
3800
3801         for (entry = ldap_first_entry(ld, msg);
3802              entry != NULL;
3803              entry = ldap_next_entry(ld, entry))
3804         {
3805                 uint32 rid;
3806                 int rid_index;
3807                 const char *attr;
3808                 enum SID_NAME_USE type;
3809                 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
3810
3811                 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
3812                                                        mem_ctx);
3813                 if (attr == NULL) {
3814                         DEBUG(2, ("Could not extract type from ldap entry %s\n",
3815                                   dn));
3816                         continue;
3817                 }
3818
3819                 type = atol(attr);
3820
3821                 /* Consistency checks */
3822                 if ((is_builtin && (type != SID_NAME_WKN_GRP)) ||
3823                     (!is_builtin && ((type != SID_NAME_ALIAS) &&
3824                                      (type != SID_NAME_DOM_GRP)))) {
3825                         DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
3826                 }
3827
3828                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
3829                                                     &rid)) {
3830                         DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
3831                         continue;
3832                 }
3833
3834                 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
3835
3836                 if (attr == NULL) {
3837                         DEBUG(10, ("Could not retrieve 'cn' attribute from %s\n",
3838                                    dn));
3839                         attr = smbldap_talloc_single_attribute(
3840                                 ld, entry, "displayName", names);
3841                 }
3842
3843                 if (attr == NULL) {
3844                         DEBUG(2, ("Could not retrieve naming attribute from %s\n",
3845                                   dn));
3846                         continue;
3847                 }
3848
3849                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3850                         if (rid == rids[rid_index])
3851                                 break;
3852                 }
3853
3854                 if (rid_index == num_rids) {
3855                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3856                         continue;
3857                 }
3858
3859                 attrs[rid_index] = type;
3860                 names[rid_index] = attr;
3861                 num_mapped += 1;
3862         }
3863
3864         result = NT_STATUS_NONE_MAPPED;
3865
3866         if (num_mapped > 0)
3867                 result = (num_mapped == num_rids) ?
3868                         NT_STATUS_OK : STATUS_SOME_UNMAPPED;
3869  done:
3870         TALLOC_FREE(mem_ctx);
3871         return result;
3872 }
3873
3874 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
3875 {
3876         char *filter = NULL;
3877         char *escaped = NULL;
3878         char *result = NULL;
3879
3880         asprintf(&filter, "(&%s(objectclass=sambaSamAccount))",
3881                  "(uid=%u)");
3882         if (filter == NULL) goto done;
3883
3884         escaped = escape_ldap_string_alloc(username);
3885         if (escaped == NULL) goto done;
3886
3887         result = talloc_string_sub(mem_ctx, filter, "%u", username);
3888
3889  done:
3890         SAFE_FREE(filter);
3891         SAFE_FREE(escaped);
3892
3893         return result;
3894 }
3895
3896 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
3897 {
3898         int i, num = 0;
3899         va_list ap;
3900         const char **result;
3901
3902         va_start(ap, mem_ctx);
3903         while (va_arg(ap, const char *) != NULL)
3904                 num += 1;
3905         va_end(ap);
3906
3907         result = TALLOC_ARRAY(mem_ctx, const char *, num+1);
3908
3909         va_start(ap, mem_ctx);
3910         for (i=0; i<num; i++)
3911                 result[i] = talloc_strdup(mem_ctx, va_arg(ap, const char*));
3912         va_end(ap);
3913
3914         result[num] = NULL;
3915         return result;
3916 }
3917
3918 struct ldap_search_state {
3919         struct smbldap_state *connection;
3920
3921         uint16 acct_flags;
3922         uint16 group_type;
3923
3924         const char *base;
3925         int scope;
3926         const char *filter;
3927         const char **attrs;
3928         int attrsonly;
3929         void *pagedresults_cookie;
3930
3931         LDAPMessage *entries, *current_entry;
3932         BOOL (*ldap2displayentry)(struct ldap_search_state *state,
3933                                   TALLOC_CTX *mem_ctx,
3934                                   LDAP *ld, LDAPMessage *entry,
3935                                   struct samr_displayentry *result);
3936 };
3937
3938 static BOOL ldapsam_search_firstpage(struct pdb_search *search)
3939 {
3940         struct ldap_search_state *state = search->private_data;
3941         LDAP *ld;
3942         int rc = LDAP_OPERATIONS_ERROR;
3943
3944         state->entries = NULL;
3945
3946         if (state->connection->paged_results) {
3947                 rc = smbldap_search_paged(state->connection, state->base,
3948                                           state->scope, state->filter,
3949                                           state->attrs, state->attrsonly,
3950                                           lp_ldap_page_size(), &state->entries,
3951                                           &state->pagedresults_cookie);
3952         }
3953
3954         if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
3955
3956                 if (state->entries != NULL) {
3957                         /* Left over from unsuccessful paged attempt */
3958                         ldap_msgfree(state->entries);
3959                         state->entries = NULL;
3960                 }
3961
3962                 rc = smbldap_search(state->connection, state->base,
3963                                     state->scope, state->filter, state->attrs,
3964                                     state->attrsonly, &state->entries);
3965
3966                 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
3967                         return False;
3968
3969                 /* Ok, the server was lying. It told us it could do paged
3970                  * searches when it could not. */
3971                 state->connection->paged_results = False;
3972         }
3973
3974         ld = state->connection->ldap_struct;
3975         if ( ld == NULL) {
3976                 DEBUG(5, ("Don't have an LDAP connection right after a "
3977                           "search\n"));
3978                 return False;
3979         }
3980         state->current_entry = ldap_first_entry(ld, state->entries);
3981
3982         if (state->current_entry == NULL) {
3983                 ldap_msgfree(state->entries);
3984                 state->entries = NULL;
3985         }
3986
3987         return True;
3988 }
3989
3990 static BOOL ldapsam_search_nextpage(struct pdb_search *search)
3991 {
3992         struct ldap_search_state *state = search->private_data;
3993         int rc;
3994
3995         if (!state->connection->paged_results) {
3996                 /* There is no next page when there are no paged results */
3997                 return False;
3998         }
3999
4000         rc = smbldap_search_paged(state->connection, state->base,
4001                                   state->scope, state->filter, state->attrs,
4002                                   state->attrsonly, lp_ldap_page_size(),
4003                                   &state->entries,
4004                                   &state->pagedresults_cookie);
4005
4006         if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4007                 return False;
4008
4009         state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4010
4011         if (state->current_entry == NULL) {
4012                 ldap_msgfree(state->entries);
4013                 state->entries = NULL;
4014         }
4015
4016         return True;
4017 }
4018
4019 static BOOL ldapsam_search_next_entry(struct pdb_search *search,
4020                                       struct samr_displayentry *entry)
4021 {
4022         struct ldap_search_state *state = search->private_data;
4023         BOOL result;
4024
4025  retry:
4026         if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4027                 return False;
4028
4029         if ((state->entries == NULL) &&
4030             !ldapsam_search_nextpage(search))
4031                     return False;
4032
4033         result = state->ldap2displayentry(state, search->mem_ctx, state->connection->ldap_struct,
4034                                           state->current_entry, entry);
4035
4036         if (!result) {
4037                 char *dn;
4038                 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4039                 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4040                 if (dn != NULL) ldap_memfree(dn);
4041         }
4042
4043         state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4044
4045         if (state->current_entry == NULL) {
4046                 ldap_msgfree(state->entries);
4047                 state->entries = NULL;
4048         }
4049
4050         if (!result) goto retry;
4051
4052         return True;
4053 }
4054
4055 static void ldapsam_search_end(struct pdb_search *search)
4056 {
4057         struct ldap_search_state *state = search->private_data;
4058         int rc;
4059
4060         if (state->pagedresults_cookie == NULL)
4061                 return;
4062
4063         if (state->entries != NULL)
4064                 ldap_msgfree(state->entries);
4065
4066         state->entries = NULL;
4067         state->current_entry = NULL;
4068
4069         if (!state->connection->paged_results)
4070                 return;
4071
4072         /* Tell the LDAP server we're not interested in the rest anymore. */
4073
4074         rc = smbldap_search_paged(state->connection, state->base, state->scope,
4075                                   state->filter, state->attrs,
4076                                   state->attrsonly, 0, &state->entries,
4077                                   &state->pagedresults_cookie);
4078
4079         if (rc != LDAP_SUCCESS)
4080                 DEBUG(5, ("Could not end search properly\n"));
4081
4082         return;
4083 }
4084
4085 static BOOL ldapuser2displayentry(struct ldap_search_state *state,
4086                                   TALLOC_CTX *mem_ctx,
4087                                   LDAP *ld, LDAPMessage *entry,
4088                                   struct samr_displayentry *result)
4089 {
4090         char **vals;
4091         DOM_SID sid;
4092         uint16 acct_flags;
4093
4094         vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4095         if ((vals == NULL) || (vals[0] == NULL)) {
4096                 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4097                 return False;
4098         }
4099         acct_flags = pdb_decode_acct_ctrl(vals[0]);
4100         ldap_value_free(vals);
4101
4102         if ((state->acct_flags != 0) &&
4103             ((state->acct_flags & acct_flags) == 0))
4104                 return False;           
4105
4106         result->acct_flags = acct_flags;
4107         result->account_name = "";
4108         result->fullname = "";
4109         result->description = "";
4110
4111         vals = ldap_get_values(ld, entry, "uid");
4112         if ((vals == NULL) || (vals[0] == NULL)) {
4113                 DEBUG(5, ("\"uid\" not found\n"));
4114                 return False;
4115         }
4116         pull_utf8_talloc(mem_ctx,
4117                          CONST_DISCARD(char **, &result->account_name),
4118                          vals[0]);
4119         ldap_value_free(vals);
4120
4121         vals = ldap_get_values(ld, entry, "displayName");
4122         if ((vals == NULL) || (vals[0] == NULL))
4123                 DEBUG(8, ("\"displayName\" not found\n"));
4124         else
4125                 pull_utf8_talloc(mem_ctx,
4126                                  CONST_DISCARD(char **, &result->fullname),
4127                                  vals[0]);
4128         ldap_value_free(vals);
4129
4130         vals = ldap_get_values(ld, entry, "description");
4131         if ((vals == NULL) || (vals[0] == NULL))
4132                 DEBUG(8, ("\"description\" not found\n"));
4133         else
4134                 pull_utf8_talloc(mem_ctx,
4135                                  CONST_DISCARD(char **, &result->description),
4136                                  vals[0]);
4137         ldap_value_free(vals);
4138
4139         if ((result->account_name == NULL) ||
4140             (result->fullname == NULL) ||
4141             (result->description == NULL)) {
4142                 DEBUG(0, ("talloc failed\n"));
4143                 return False;
4144         }
4145         
4146         vals = ldap_get_values(ld, entry, "sambaSid");
4147         if ((vals == NULL) || (vals[0] == NULL)) {
4148                 DEBUG(0, ("\"objectSid\" not found\n"));
4149                 return False;
4150         }
4151
4152         if (!string_to_sid(&sid, vals[0])) {
4153                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4154                 ldap_value_free(vals);
4155                 return False;
4156         }
4157         ldap_value_free(vals);
4158
4159         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4160                 DEBUG(0, ("sid %s does not belong to our domain\n",
4161                           sid_string_static(&sid)));
4162                 return False;
4163         }
4164
4165         return True;
4166 }
4167
4168
4169 static BOOL ldapsam_search_users(struct pdb_methods *methods,
4170                                  struct pdb_search *search,
4171                                  uint16 acct_flags)
4172 {
4173         struct ldapsam_privates *ldap_state = methods->private_data;
4174         struct ldap_search_state *state;
4175
4176         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4177         if (state == NULL) {
4178                 DEBUG(0, ("talloc failed\n"));
4179                 return False;
4180         }
4181
4182         state->connection = ldap_state->smbldap_state;
4183
4184         if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4185                 state->base = lp_ldap_user_suffix();
4186         else if ((acct_flags != 0) &&
4187                  ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4188                 state->base = lp_ldap_machine_suffix();
4189         else
4190                 state->base = lp_ldap_suffix();
4191
4192         state->acct_flags = acct_flags;
4193         state->base = talloc_strdup(search->mem_ctx, state->base);
4194         state->scope = LDAP_SCOPE_SUBTREE;
4195         state->filter = get_ldap_filter(search->mem_ctx, "*");
4196         state->attrs = talloc_attrs(search->mem_ctx, "uid", "sambaSid",
4197                                     "displayName", "description",
4198                                     "sambaAcctFlags", NULL);
4199         state->attrsonly = 0;
4200         state->pagedresults_cookie = NULL;
4201         state->entries = NULL;
4202         state->ldap2displayentry = ldapuser2displayentry;
4203
4204         if ((state->filter == NULL) || (state->attrs == NULL)) {
4205                 DEBUG(0, ("talloc failed\n"));
4206                 return False;
4207         }
4208
4209         search->private_data = state;
4210         search->next_entry = ldapsam_search_next_entry;
4211         search->search_end = ldapsam_search_end;
4212
4213         return ldapsam_search_firstpage(search);
4214 }
4215
4216 static BOOL ldapgroup2displayentry(struct ldap_search_state *state,
4217                                    TALLOC_CTX *mem_ctx,
4218                                    LDAP *ld, LDAPMessage *entry,
4219                                    struct samr_displayentry *result)
4220 {
4221         char **vals;
4222         DOM_SID sid;
4223         uint16 group_type;
4224
4225         result->account_name = "";
4226         result->fullname = "";
4227         result->description = "";
4228
4229
4230         vals = ldap_get_values(ld, entry, "sambaGroupType");
4231         if ((vals == NULL) || (vals[0] == NULL)) {
4232                 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4233                 if (vals != NULL) {
4234                         ldap_value_free(vals);
4235                 }
4236                 return False;
4237         }
4238
4239         group_type = atoi(vals[0]);
4240
4241         if ((state->group_type != 0) &&
4242             ((state->group_type != group_type))) {
4243                 ldap_value_free(vals);
4244                 return False;
4245         }
4246
4247         ldap_value_free(vals);
4248
4249         /* display name is the NT group name */
4250
4251         vals = ldap_get_values(ld, entry, "displayName");
4252         if ((vals == NULL) || (vals[0] == NULL)) {
4253                 DEBUG(8, ("\"displayName\" not found\n"));
4254
4255                 /* fallback to the 'cn' attribute */
4256                 vals = ldap_get_values(ld, entry, "cn");
4257                 if ((vals == NULL) || (vals[0] == NULL)) {
4258                         DEBUG(5, ("\"cn\" not found\n"));
4259                         return False;
4260                 }
4261                 pull_utf8_talloc(mem_ctx,
4262                                  CONST_DISCARD(char **, &result->account_name),
4263                                  vals[0]);
4264         }
4265         else {
4266                 pull_utf8_talloc(mem_ctx,
4267                                  CONST_DISCARD(char **, &result->account_name),
4268                                  vals[0]);
4269         }
4270
4271         ldap_value_free(vals);
4272
4273         vals = ldap_get_values(ld, entry, "description");
4274         if ((vals == NULL) || (vals[0] == NULL))
4275                 DEBUG(8, ("\"description\" not found\n"));
4276         else
4277                 pull_utf8_talloc(mem_ctx,
4278                                  CONST_DISCARD(char **, &result->description),
4279                                  vals[0]);
4280         ldap_value_free(vals);
4281
4282         if ((result->account_name == NULL) ||
4283             (result->fullname == NULL) ||
4284             (result->description == NULL)) {
4285                 DEBUG(0, ("talloc failed\n"));
4286                 return False;
4287         }
4288         
4289         vals = ldap_get_values(ld, entry, "sambaSid");
4290         if ((vals == NULL) || (vals[0] == NULL)) {
4291                 DEBUG(0, ("\"objectSid\" not found\n"));
4292                 if (vals != NULL) {
4293                         ldap_value_free(vals);
4294                 }
4295                 return False;
4296         }
4297
4298         if (!string_to_sid(&sid, vals[0])) {
4299                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4300                 return False;
4301         }
4302
4303         ldap_value_free(vals);
4304
4305         switch (group_type) {
4306                 case SID_NAME_DOM_GRP:
4307                 case SID_NAME_ALIAS:
4308
4309                         if (!sid_peek_check_rid(get_global_sam_sid(), &sid,
4310                                                 &result->rid)) {
4311                                 DEBUG(0, ("%s is not in our domain\n",
4312                                           sid_string_static(&sid)));
4313                                 return False;
4314                         }
4315                         break;
4316         
4317                 case SID_NAME_WKN_GRP:
4318
4319                         if (!sid_peek_check_rid(&global_sid_Builtin, &sid,
4320                                                 &result->rid)) {
4321
4322                                 DEBUG(0, ("%s is not in builtin sid\n",
4323                                           sid_string_static(&sid)));
4324                                 return False;
4325                         }
4326                         break;
4327
4328                 default:
4329                         DEBUG(0,("unkown group type: %d\n", group_type));
4330                         return False;
4331         }
4332         
4333         return True;
4334 }
4335
4336 static BOOL ldapsam_search_grouptype(struct pdb_methods *methods,
4337                                      struct pdb_search *search,
4338                                      enum SID_NAME_USE type)
4339 {
4340         struct ldapsam_privates *ldap_state = methods->private_data;
4341         struct ldap_search_state *state;
4342
4343         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4344         if (state == NULL) {
4345                 DEBUG(0, ("talloc failed\n"));
4346                 return False;
4347         }
4348
4349         state->connection = ldap_state->smbldap_state;
4350
4351         state->base = talloc_strdup(search->mem_ctx, lp_ldap_group_suffix());
4352         state->connection = ldap_state->smbldap_state;
4353         state->scope = LDAP_SCOPE_SUBTREE;
4354         state->filter = talloc_asprintf(search->mem_ctx,
4355                                         "(&(objectclass=sambaGroupMapping)"
4356                                         "(sambaGroupType=%d))", type);
4357         state->attrs = talloc_attrs(search->mem_ctx, "cn", "sambaSid",
4358                                     "displayName", "description",
4359                                     "sambaGroupType", NULL);
4360         state->attrsonly = 0;
4361         state->pagedresults_cookie = NULL;
4362         state->entries = NULL;
4363         state->group_type = type;
4364         state->ldap2displayentry = ldapgroup2displayentry;
4365
4366         if ((state->filter == NULL) || (state->attrs == NULL)) {
4367                 DEBUG(0, ("talloc failed\n"));
4368                 return False;
4369         }
4370
4371         search->private_data = state;
4372         search->next_entry = ldapsam_search_next_entry;
4373         search->search_end = ldapsam_search_end;
4374
4375         return ldapsam_search_firstpage(search);
4376 }
4377
4378 static BOOL ldapsam_search_groups(struct pdb_methods *methods,
4379                                   struct pdb_search *search)
4380 {
4381         return ldapsam_search_grouptype(methods, search, SID_NAME_DOM_GRP);
4382 }
4383
4384 static BOOL ldapsam_search_aliases(struct pdb_methods *methods,
4385                                    struct pdb_search *search,
4386                                    const DOM_SID *sid)
4387 {
4388         if (sid_check_is_domain(sid))
4389                 return ldapsam_search_grouptype(methods, search,
4390                                                 SID_NAME_ALIAS);
4391
4392         if (sid_check_is_builtin(sid))
4393                 return ldapsam_search_grouptype(methods, search,
4394                                                 SID_NAME_WKN_GRP);
4395
4396         DEBUG(5, ("Don't know SID %s\n", sid_string_static(sid)));
4397         return False;
4398 }
4399
4400 static BOOL ldapsam_rid_algorithm(struct pdb_methods *methods)
4401 {
4402         return False;
4403 }
4404
4405 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4406                                     uint32 *rid)
4407 {
4408         struct smbldap_state *smbldap_state = priv->smbldap_state;
4409
4410         LDAPMessage *result = NULL;
4411         LDAPMessage *entry = NULL;
4412         LDAPMod **mods = NULL;
4413         NTSTATUS status;
4414         char *value;
4415         int rc;
4416         uint32 nextRid = 0;
4417
4418         TALLOC_CTX *mem_ctx;
4419
4420         mem_ctx = talloc_new(NULL);
4421         if (mem_ctx == NULL) {
4422                 DEBUG(0, ("talloc_new failed\n"));
4423                 return NT_STATUS_NO_MEMORY;
4424         }
4425
4426         status = smbldap_search_domain_info(smbldap_state, &result,
4427                                             get_global_sam_name(), False);
4428         if (!NT_STATUS_IS_OK(status)) {
4429                 DEBUG(3, ("Could not get domain info: %s\n",
4430                           nt_errstr(status)));
4431                 goto done;
4432         }
4433
4434         talloc_autofree_ldapmsg(mem_ctx, result);
4435
4436         entry = ldap_first_entry(priv2ld(priv), result);
4437         if (entry == NULL) {
4438                 DEBUG(0, ("Could not get domain info entry\n"));
4439                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4440                 goto done;
4441         }
4442
4443         /* Find the largest of the three attributes "sambaNextRid",
4444            "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4445            concept of differentiating between user and group rids, and will
4446            use only "sambaNextRid" in the future. But for compatibility
4447            reasons I look if others have chosen different strategies -- VL */
4448
4449         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4450                                                 "sambaNextRid", mem_ctx);
4451         if (value != NULL) {
4452                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4453                 nextRid = MAX(nextRid, tmp);
4454         }
4455
4456         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4457                                                 "sambaNextUserRid", mem_ctx);
4458         if (value != NULL) {
4459                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4460                 nextRid = MAX(nextRid, tmp);
4461         }
4462
4463         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4464                                                 "sambaNextGroupRid", mem_ctx);
4465         if (value != NULL) {
4466                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4467                 nextRid = MAX(nextRid, tmp);
4468         }
4469
4470         if (nextRid == 0) {
4471                 nextRid = BASE_RID-1;
4472         }
4473
4474         nextRid += 1;
4475
4476         smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4477                          talloc_asprintf(mem_ctx, "%d", nextRid));
4478         talloc_autofree_ldapmod(mem_ctx, mods);
4479
4480         rc = smbldap_modify(smbldap_state,
4481                             smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry),
4482                             mods);
4483
4484         /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4485          * please retry" */
4486
4487         status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4488
4489  done:
4490         if (NT_STATUS_IS_OK(status)) {
4491                 *rid = nextRid;
4492         }
4493
4494         TALLOC_FREE(mem_ctx);
4495         return status;
4496 }
4497
4498 static BOOL ldapsam_new_rid(struct pdb_methods *methods, uint32 *rid)
4499 {
4500         int i;
4501
4502         for (i=0; i<10; i++) {
4503                 NTSTATUS result = ldapsam_get_new_rid(methods->private_data,
4504                                                       rid);
4505                 if (NT_STATUS_IS_OK(result)) {
4506                         return True;
4507                 }
4508
4509                 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4510                         return False;
4511                 }
4512
4513                 /* The ldap update failed (maybe a race condition), retry */
4514         }
4515
4516         /* Tried 10 times, fail. */
4517         return False;
4518 }
4519
4520 static BOOL ldapsam_sid_to_id(struct pdb_methods *methods,
4521                               const DOM_SID *sid,
4522                               union unid_t *id, enum SID_NAME_USE *type)
4523 {
4524         struct ldapsam_privates *priv = methods->private_data;
4525         char *filter;
4526         const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4527                                 NULL };
4528         LDAPMessage *result = NULL;
4529         LDAPMessage *entry = NULL;
4530         BOOL ret = False;
4531         char *value;
4532         int rc;
4533
4534         TALLOC_CTX *mem_ctx;
4535
4536         mem_ctx = talloc_new(NULL);
4537         if (mem_ctx == NULL) {
4538                 DEBUG(0, ("talloc_new failed\n"));
4539                 return False;
4540         }
4541
4542         filter = talloc_asprintf(mem_ctx,
4543                                  "(&(sambaSid=%s)"
4544                                  "(|(objectClass=sambaGroupMapping)"
4545                                  "(objectClass=sambaSamAccount)))",
4546                                  sid_string_static(sid));
4547         if (filter == NULL) {
4548                 DEBUG(5, ("talloc_asprintf failed\n"));
4549                 goto done;
4550         }
4551
4552         rc = smbldap_search_suffix(priv->smbldap_state, filter,
4553                                    attrs, &result);
4554         if (rc != LDAP_SUCCESS) {
4555                 goto done;
4556         }
4557         talloc_autofree_ldapmsg(mem_ctx, result);
4558
4559         if (ldap_count_entries(priv2ld(priv), result) != 1) {
4560                 DEBUG(10, ("Got %d entries, expected one\n",
4561                            ldap_count_entries(priv2ld(priv), result)));
4562                 goto done;
4563         }
4564
4565         entry = ldap_first_entry(priv2ld(priv), result);
4566
4567         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4568                                                 "sambaGroupType", mem_ctx);
4569
4570         if (value != NULL) {
4571                 const char *gid_str;
4572                 /* It's a group */
4573
4574                 gid_str = smbldap_talloc_single_attribute(
4575                         priv2ld(priv), entry, "gidNumber", mem_ctx);
4576                 if (gid_str == NULL) {
4577                         DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4578                                   smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4579                                                     entry)));
4580                         goto done;
4581                 }
4582
4583                 id->gid = strtoul(gid_str, NULL, 10);
4584                 *type = strtoul(value, NULL, 10);
4585                 ret = True;
4586                 goto done;
4587         }
4588
4589         /* It must be a user */
4590
4591         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4592                                                 "uidNumber", mem_ctx);
4593         if (value == NULL) {
4594                 DEBUG(1, ("Could not find uidNumber in %s\n",
4595                           smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4596                 goto done;
4597         }
4598
4599         id->uid = strtoul(value, NULL, 10);
4600         *type = SID_NAME_USER;
4601
4602         ret = True;
4603  done:
4604         TALLOC_FREE(mem_ctx);
4605         return ret;
4606 }
4607
4608 /**********************************************************************
4609  Housekeeping
4610  *********************************************************************/
4611
4612 static void free_private_data(void **vp) 
4613 {
4614         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
4615
4616         smbldap_free_struct(&(*ldap_state)->smbldap_state);
4617
4618         if ((*ldap_state)->result != NULL) {
4619                 ldap_msgfree((*ldap_state)->result);
4620                 (*ldap_state)->result = NULL;
4621         }
4622         if ((*ldap_state)->domain_dn != NULL) {
4623                 SAFE_FREE((*ldap_state)->domain_dn);
4624         }
4625
4626         *ldap_state = NULL;
4627
4628         /* No need to free any further, as it is talloc()ed */
4629 }
4630
4631 /*********************************************************************
4632  Intitalise the parts of the pdb_methods structure that are common to 
4633  all pdb_ldap modes
4634 *********************************************************************/
4635
4636 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
4637 {
4638         NTSTATUS nt_status;
4639         struct ldapsam_privates *ldap_state;
4640
4641         if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
4642                 return nt_status;
4643         }
4644
4645         (*pdb_method)->name = "ldapsam";
4646
4647         (*pdb_method)->setsampwent = ldapsam_setsampwent;
4648         (*pdb_method)->endsampwent = ldapsam_endsampwent;
4649         (*pdb_method)->getsampwent = ldapsam_getsampwent;
4650         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
4651         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
4652         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
4653         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
4654         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
4655         (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
4656
4657         (*pdb_method)->getgrsid = ldapsam_getgrsid;
4658         (*pdb_method)->getgrgid = ldapsam_getgrgid;
4659         (*pdb_method)->getgrnam = ldapsam_getgrnam;
4660         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
4661         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
4662         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
4663         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
4664
4665         (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
4666         (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
4667
4668         (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
4669
4670         (*pdb_method)->rid_algorithm = ldapsam_rid_algorithm;
4671         (*pdb_method)->new_rid = ldapsam_new_rid;
4672
4673         /* TODO: Setup private data and free */
4674
4675         if ( !(ldap_state = TALLOC_ZERO_P(*pdb_method, struct ldapsam_privates)) ) {
4676                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
4677                 return NT_STATUS_NO_MEMORY;
4678         }
4679
4680         nt_status = smbldap_init(*pdb_method, location, &ldap_state->smbldap_state);
4681
4682         if ( !NT_STATUS_IS_OK(nt_status) ) {
4683                 return nt_status;
4684         }
4685
4686         if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
4687                 return NT_STATUS_NO_MEMORY;
4688         }
4689
4690         (*pdb_method)->private_data = ldap_state;
4691
4692         (*pdb_method)->free_private_data = free_private_data;
4693
4694         return NT_STATUS_OK;
4695 }
4696
4697 /**********************************************************************
4698  Initialise the 'compat' mode for pdb_ldap
4699  *********************************************************************/
4700
4701 NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
4702 {
4703         NTSTATUS nt_status;
4704         struct ldapsam_privates *ldap_state;
4705         char *uri = talloc_strdup( NULL, location );
4706
4707 #ifdef WITH_LDAP_SAMCONFIG
4708         if (!uri) {
4709                 int ldap_port = lp_ldap_port();
4710                         
4711                 /* remap default port if not using SSL (ie clear or TLS) */
4712                 if ( (lp_ldap_ssl() != LDAP_SSL_ON) && (ldap_port == 636) ) {
4713                         ldap_port = 389;
4714                 }
4715
4716                 uri = talloc_asprintf(NULL, "%s://%s:%d", lp_ldap_ssl() == LDAP_SSL_ON ? "ldaps" : "ldap", lp_ldap_server(), ldap_port);
4717                 if (!uri) {
4718                         return NT_STATUS_NO_MEMORY;
4719                 }
4720                 location = uri;
4721         }
4722 #endif
4723
4724         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common( pdb_method, uri ))) {
4725                 return nt_status;
4726         }
4727
4728         /* the module itself stores a copy of the location so throw this one away */
4729
4730         if ( uri )
4731                 TALLOC_FREE( uri );
4732
4733         (*pdb_method)->name = "ldapsam_compat";
4734
4735         ldap_state = (*pdb_method)->private_data;
4736         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
4737
4738         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
4739
4740         return NT_STATUS_OK;
4741 }
4742
4743 /**********************************************************************
4744  Initialise the normal mode for pdb_ldap
4745  *********************************************************************/
4746
4747 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
4748 {
4749         NTSTATUS nt_status;
4750         struct ldapsam_privates *ldap_state;
4751         uint32 alg_rid_base;
4752         pstring alg_rid_base_string;
4753         LDAPMessage *result = NULL;
4754         LDAPMessage *entry = NULL;
4755         DOM_SID ldap_domain_sid;
4756         DOM_SID secrets_domain_sid;
4757         pstring domain_sid_string;
4758         char *dn;
4759
4760         nt_status = pdb_init_ldapsam_common(pdb_method, location);
4761         if (!NT_STATUS_IS_OK(nt_status)) {
4762                 return nt_status;
4763         }
4764
4765         (*pdb_method)->name = "ldapsam";
4766
4767         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
4768         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
4769         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
4770         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
4771         (*pdb_method)->search_users = ldapsam_search_users;
4772         (*pdb_method)->search_groups = ldapsam_search_groups;
4773         (*pdb_method)->search_aliases = ldapsam_search_aliases;
4774
4775         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
4776                 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
4777                 (*pdb_method)->enum_group_memberships =
4778                         ldapsam_enum_group_memberships;
4779                 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
4780                 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
4781         }
4782
4783         ldap_state = (*pdb_method)->private_data;
4784         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
4785
4786         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
4787         
4788         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
4789                                                &result, 
4790                                                ldap_state->domain_name, True);
4791         
4792         if ( !NT_STATUS_IS_OK(nt_status) ) {
4793                 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain "
4794                           "info, nor add one to the domain\n"));
4795                 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, "
4796                              "will be unable to allocate new users/groups, "
4797                              "and will risk BDCs having inconsistant SIDs\n"));
4798                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
4799                 return NT_STATUS_OK;
4800         }
4801
4802         /* Given that the above might fail, everything below this must be
4803          * optional */
4804         
4805         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
4806                                  result);
4807         if (!entry) {
4808                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
4809                           "entry\n"));
4810                 ldap_msgfree(result);
4811                 return NT_STATUS_UNSUCCESSFUL;
4812         }
4813
4814         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
4815         if (!dn) {
4816                 return NT_STATUS_UNSUCCESSFUL;
4817         }
4818
4819         ldap_state->domain_dn = smb_xstrdup(dn);
4820         ldap_memfree(dn);
4821
4822         if (smbldap_get_single_pstring(
4823                     ldap_state->smbldap_state->ldap_struct,
4824                     entry, 
4825                     get_userattr_key2string(ldap_state->schema_ver,
4826                                             LDAP_ATTR_USER_SID), 
4827                     domain_sid_string)) {
4828                 BOOL found_sid;
4829                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
4830                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
4831                                   "read as a valid SID\n", domain_sid_string));
4832                         return NT_STATUS_INVALID_PARAMETER;
4833                 }
4834                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
4835                                                      &secrets_domain_sid);
4836                 if (!found_sid || !sid_equal(&secrets_domain_sid,
4837                                              &ldap_domain_sid)) {
4838                         fstring new_sid_str, old_sid_str;
4839                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
4840                                   "%s based on pdb_ldap results %s -> %s\n",
4841                                   ldap_state->domain_name,
4842                                   sid_to_string(old_sid_str,
4843                                                 &secrets_domain_sid),
4844                                   sid_to_string(new_sid_str,
4845                                                 &ldap_domain_sid)));
4846                         
4847                         /* reset secrets.tdb sid */
4848                         secrets_store_domain_sid(ldap_state->domain_name,
4849                                                  &ldap_domain_sid);
4850                         DEBUG(1, ("New global sam SID: %s\n",
4851                                   sid_to_string(new_sid_str,
4852                                                 get_global_sam_sid())));
4853                 }
4854                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
4855         }
4856
4857         if (smbldap_get_single_pstring(
4858                     ldap_state->smbldap_state->ldap_struct,
4859                     entry, 
4860                     get_attr_key2string( dominfo_attr_list,
4861                                          LDAP_ATTR_ALGORITHMIC_RID_BASE ),
4862                     alg_rid_base_string)) {
4863                 alg_rid_base = (uint32)atol(alg_rid_base_string);
4864                 if (alg_rid_base != algorithmic_rid_base()) {
4865                         DEBUG(0, ("The value of 'algorithmic RID base' has "
4866                                   "changed since the LDAP\n"
4867                                   "database was initialised.  Aborting. \n"));
4868                         ldap_msgfree(result);
4869                         return NT_STATUS_UNSUCCESSFUL;
4870                 }
4871         }
4872         ldap_msgfree(result);
4873
4874         return NT_STATUS_OK;
4875 }
4876
4877 NTSTATUS pdb_ldap_init(void)
4878 {
4879         NTSTATUS nt_status;
4880         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
4881                 return nt_status;
4882
4883         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
4884                 return nt_status;
4885
4886         /* Let pdb_nds register backends */
4887         pdb_nds_init();
4888
4889         return NT_STATUS_OK;
4890 }