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