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