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