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