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