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