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