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