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