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