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