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