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