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