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