Fix usage of va_list passed as an arg. Use __va_copy before using it
[kai/samba.git] / source3 / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/CIFS implementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Gerald Carter 2001
5    Copyright (C) Shahms King 2001
6    Copyright (C) Jean François Micouleau 1998
7    Copyright (C) Andrew Bartlett 2002
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22    
23 */
24
25 #include "includes.h"
26
27 #ifdef WITH_LDAP_SAM
28 /* TODO:
29 *  persistent connections: if using NSS LDAP, many connections are made
30 *      however, using only one within Samba would be nice
31 *  
32 *  Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
33 *
34 *  Other LDAP based login attributes: accountExpires, etc.
35 *  (should be the domain of Samba proper, but the sam_password/SAM_ACCOUNT
36 *  structures don't have fields for some of these attributes)
37 *
38 *  SSL is done, but can't get the certificate based authentication to work
39 *  against on my test platform (Linux 2.4, OpenLDAP 2.x)
40 */
41
42 /* NOTE: this will NOT work against an Active Directory server
43 *  due to the fact that the two password fields cannot be retrieved
44 *  from a server; recommend using security = domain in this situation
45 *  and/or winbind
46 */
47
48 #include <lber.h>
49 #include <ldap.h>
50
51 #ifndef SAM_ACCOUNT
52 #define SAM_ACCOUNT struct sam_passwd
53 #endif
54
55 struct ldapsam_privates {
56
57         /* Former statics */
58         LDAP *ldap_struct;
59         LDAPMessage *result;
60         LDAPMessage *entry;
61         int index;
62         
63         /* retrive-once info */
64         const char *uri;
65         
66         BOOL permit_non_unix_accounts;
67         
68         uint32 low_nua_rid; 
69         uint32 high_nua_rid; 
70 };
71
72 static uint32 ldapsam_get_next_available_nua_rid(struct ldapsam_privates *ldap_state);
73
74 /*******************************************************************
75  find the ldap password
76 ******************************************************************/
77 static BOOL fetch_ldapsam_pw(char *dn, char* pw, int len)
78 {
79         fstring key;
80         char *p;
81         void *data = NULL;
82         size_t size;
83         
84         pstrcpy(key, dn);
85         for (p=key; *p; p++)
86                 if (*p == ',') *p = '/';
87         
88         data=secrets_fetch(key, &size);
89         if (!size) {
90                 DEBUG(0,("fetch_ldap_pw: no ldap secret retrieved!\n"));
91                 return False;
92         }
93         
94         if (size > len-1)
95         {
96                 DEBUG(0,("fetch_ldap_pw: ldap secret is too long (%d > %d)!\n", size, len-1));
97                 return False;
98         }
99
100         memcpy(pw, data, size);
101         pw[size] = '\0';
102         
103         return True;
104 }
105
106
107 /*******************************************************************
108  open a connection to the ldap server.
109 ******************************************************************/
110 static BOOL ldapsam_open_connection (struct ldapsam_privates *ldap_state, LDAP ** ldap_struct)
111 {
112
113         if (geteuid() != 0) {
114                 DEBUG(0, ("ldap_open_connection: cannot access LDAP when not root..\n"));
115                 return False;
116         }
117         
118 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
119         DEBUG(10, ("ldapsam_open_connection: %s\n", ldap_state->uri));
120         
121         if (ldap_initialize(ldap_struct, ldap_state->uri) != LDAP_SUCCESS) {
122                 DEBUG(0, ("ldap_initialize: %s\n", strerror(errno)));
123                 return (False);
124         }
125 #else 
126
127         /* Parse the string manually */
128
129         {
130                 int rc;
131                 int tls = LDAP_OPT_X_TLS_HARD;
132                 int port = 0;
133                 int version;
134                 fstring protocol;
135                 fstring host;
136                 const char *p = ldap_state->uri; 
137                 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
138                 
139                 /* skip leading "URL:" (if any) */
140                 if ( strncasecmp( p, "URL:", 4 ) == 0 ) {
141                         p += 4;
142                 }
143
144                 sscanf(p, "%10[^:]://%254s[^:]:%d", protocol, host, &port);
145                 
146                 if (port == 0) {
147                         if (strequal(protocol, "ldap")) {
148                                 port = LDAP_PORT;
149                         } else if (strequal(protocol, "ldaps")) {
150                                 port = LDAPS_PORT;
151                         } else {
152                                 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
153                         }
154                 }
155
156                 if ((*ldap_struct = ldap_init(host, port)) == NULL)     {
157                         DEBUG(0, ("ldap_init failed !\n"));
158                         return False;
159                 }
160
161                 /* Connect to older servers using SSL and V2 rather than Start TLS */
162                 if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
163                 {
164                         if (version != LDAP_VERSION2)
165                         {
166                                 version = LDAP_VERSION2;
167                                 ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
168                         }
169                 }
170
171                 if (strequal(protocol, "ldaps")) { 
172                         if (lp_ldap_ssl() == LDAP_SSL_START_TLS) {
173                                 if (ldap_get_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, 
174                                                      &version) == LDAP_OPT_SUCCESS)
175                                 {
176                                         if (version < LDAP_VERSION3)
177                                         {
178                                                 version = LDAP_VERSION3;
179                                                 ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION,
180                                                                  &version);
181                                         }
182                                 }
183                                 if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
184                                 {
185                                         DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
186                                                  ldap_err2string(rc)));
187                                         return False;
188                                 }
189                                 DEBUG (2, ("StartTLS issued: using a TLS connection\n"));
190                         } else {
191                                 
192                                 if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
193                                 {
194                                         DEBUG(0, ("Failed to setup a TLS session\n"));
195                                 }
196                         }
197                 } else {
198                         /* 
199                          * No special needs to setup options prior to the LDAP
200                          * bind (which should be called next via ldap_connect_system()
201                          */
202                 }
203         }
204 #endif
205
206         DEBUG(2, ("ldap_open_connection: connection opened\n"));
207         return True;
208 }
209
210 /*******************************************************************
211  connect to the ldap server under system privilege.
212 ******************************************************************/
213 static BOOL ldapsam_connect_system(struct ldapsam_privates *ldap_state, LDAP * ldap_struct)
214 {
215         int rc;
216         static BOOL got_pw = False;
217         static pstring ldap_secret;
218
219         /* get the password if we don't have it already */
220         if (!got_pw && !(got_pw=fetch_ldapsam_pw(lp_ldap_admin_dn(), ldap_secret, sizeof(pstring)))) 
221         {
222                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password for %s from secrets.tdb\n",
223                         lp_ldap_admin_dn()));
224                 return False;
225         }
226
227         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
228            (OpenLDAP) doesnt' seem to support it */
229            
230         DEBUG(10,("ldap_connect_system: Binding to ldap server as \"%s\"\n",
231                 lp_ldap_admin_dn()));
232                 
233         if ((rc = ldap_simple_bind_s(ldap_struct, lp_ldap_admin_dn(), 
234                 ldap_secret)) != LDAP_SUCCESS)
235         {
236                 DEBUG(0, ("Bind failed: %s\n", ldap_err2string(rc)));
237                 return False;
238         }
239         
240         DEBUG(2, ("ldap_connect_system: successful connection to the LDAP server\n"));
241         return True;
242 }
243
244 /*******************************************************************
245  run the search by name.
246 ******************************************************************/
247 static int ldapsam_search_one_user (struct ldapsam_privates *ldap_state, LDAP * ldap_struct, const char *filter, LDAPMessage ** result)
248 {
249         int scope = LDAP_SCOPE_SUBTREE;
250         int rc;
251
252         DEBUG(2, ("ldapsam_search_one_user: searching for:[%s]\n", filter));
253
254         rc = ldap_search_s(ldap_struct, lp_ldap_suffix (), scope, filter, NULL, 0, result);
255
256         if (rc != LDAP_SUCCESS) {
257                 DEBUG(0,("ldapsam_search_one_user: Problem during the LDAP search: %s\n", 
258                         ldap_err2string (rc)));
259                 DEBUG(3,("ldapsam_search_one_user: Query was: %s, %s\n", lp_ldap_suffix(), 
260                         filter));
261         }
262         
263         return rc;
264 }
265
266 /*******************************************************************
267  run the search by name.
268 ******************************************************************/
269 static int ldapsam_search_one_user_by_name (struct ldapsam_privates *ldap_state, LDAP * ldap_struct, const char *user,
270                              LDAPMessage ** result)
271 {
272         pstring filter;
273         
274         /*
275          * in the filter expression, replace %u with the real name
276          * so in ldap filter, %u MUST exist :-)
277          */
278         pstrcpy(filter, lp_ldap_filter());
279
280         /* 
281          * have to use this here because $ is filtered out
282            * in pstring_sub
283          */
284         all_string_sub(filter, "%u", user, sizeof(pstring));
285
286         return ldapsam_search_one_user(ldap_state, ldap_struct, filter, result);
287 }
288
289 /*******************************************************************
290  run the search by uid.
291 ******************************************************************/
292 static int ldapsam_search_one_user_by_uid(struct ldapsam_privates *ldap_state, 
293                                           LDAP * ldap_struct, int uid,
294                                           LDAPMessage ** result)
295 {
296         struct passwd *user;
297         pstring filter;
298
299         /* Get the username from the system and look that up in the LDAP */
300         
301         if ((user = getpwuid_alloc(uid)) == NULL) {
302                 DEBUG(3,("ldapsam_search_one_user_by_uid: Failed to locate uid [%d]\n", uid));
303                 return LDAP_NO_SUCH_OBJECT;
304         }
305         
306         pstrcpy(filter, lp_ldap_filter());
307         
308         all_string_sub(filter, "%u", user->pw_name, sizeof(pstring));
309
310         passwd_free(&user);
311
312         return ldapsam_search_one_user(ldap_state, ldap_struct, filter, result);
313 }
314
315 /*******************************************************************
316  run the search by rid.
317 ******************************************************************/
318 static int ldapsam_search_one_user_by_rid (struct ldapsam_privates *ldap_state, 
319                                            LDAP * ldap_struct, uint32 rid,
320                                            LDAPMessage ** result)
321 {
322         pstring filter;
323         int rc;
324
325         /* check if the user rid exsists, if not, try searching on the uid */
326         
327         snprintf(filter, sizeof(filter) - 1, "rid=%i", rid);
328         rc = ldapsam_search_one_user(ldap_state, ldap_struct, filter, result);
329         
330         if (rc != LDAP_SUCCESS)
331                 rc = ldapsam_search_one_user_by_uid(ldap_state, ldap_struct, 
332                                                     fallback_pdb_user_rid_to_uid(rid), 
333                                                     result);
334
335         return rc;
336 }
337
338 /*******************************************************************
339 search an attribute and return the first value found.
340 ******************************************************************/
341 static BOOL get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
342                                   char *attribute, char *value)
343 {
344         char **values;
345
346         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
347                 value = NULL;
348                 DEBUG (10, ("get_single_attribute: [%s] = [<does not exist>]\n", attribute));
349                 
350                 return False;
351         }
352         
353         pstrcpy(value, values[0]);
354         ldap_value_free(values);
355 #ifdef DEBUG_PASSWORDS
356         DEBUG (100, ("get_single_attribute: [%s] = [%s]\n", attribute, value));
357 #endif  
358         return True;
359 }
360
361 /************************************************************************
362 Routine to manage the LDAPMod structure array
363 manage memory used by the array, by each struct, and values
364
365 ************************************************************************/
366 static void make_a_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
367 {
368         LDAPMod **mods;
369         int i;
370         int j;
371
372         mods = *modlist;
373
374         if (attribute == NULL || *attribute == '\0')
375                 return;
376
377         if (value == NULL || *value == '\0')
378                 return;
379
380         if (mods == NULL) 
381         {
382                 mods = (LDAPMod **) malloc(sizeof(LDAPMod *));
383                 if (mods == NULL)
384                 {
385                         DEBUG(0, ("make_a_mod: out of memory!\n"));
386                         return;
387                 }
388                 mods[0] = NULL;
389         }
390
391         for (i = 0; mods[i] != NULL; ++i) {
392                 if (mods[i]->mod_op == modop && !strcasecmp(mods[i]->mod_type, attribute))
393                         break;
394         }
395
396         if (mods[i] == NULL)
397         {
398                 mods = (LDAPMod **) Realloc (mods, (i + 2) * sizeof (LDAPMod *));
399                 if (mods == NULL)
400                 {
401                         DEBUG(0, ("make_a_mod: out of memory!\n"));
402                         return;
403                 }
404                 mods[i] = (LDAPMod *) malloc(sizeof(LDAPMod));
405                 if (mods[i] == NULL)
406                 {
407                         DEBUG(0, ("make_a_mod: out of memory!\n"));
408                         return;
409                 }
410                 mods[i]->mod_op = modop;
411                 mods[i]->mod_values = NULL;
412                 mods[i]->mod_type = strdup(attribute);
413                 mods[i + 1] = NULL;
414         }
415
416         if (value != NULL)
417         {
418                 j = 0;
419                 if (mods[i]->mod_values != NULL) {
420                         for (; mods[i]->mod_values[j] != NULL; j++);
421                 }
422                 mods[i]->mod_values = (char **)Realloc(mods[i]->mod_values,
423                                                (j + 2) * sizeof (char *));
424                                                
425                 if (mods[i]->mod_values == NULL) {
426                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
427                         return;
428                 }
429                 mods[i]->mod_values[j] = strdup(value);
430                 mods[i]->mod_values[j + 1] = NULL;
431         }
432         *modlist = mods;
433 }
434
435 /* New Interface is being implemented here */
436
437 /**********************************************************************
438 Initialize SAM_ACCOUNT from an LDAP query
439 (Based on init_sam_from_buffer in pdb_tdb.c)
440 *********************************************************************/
441 static BOOL init_sam_from_ldap (struct ldapsam_privates *ldap_state, 
442                                 SAM_ACCOUNT * sampass,
443                                 LDAP * ldap_struct, LDAPMessage * entry)
444 {
445         time_t  logon_time,
446                         logoff_time,
447                         kickoff_time,
448                         pass_last_set_time, 
449                         pass_can_change_time, 
450                         pass_must_change_time;
451         pstring         username, 
452                         domain,
453                         nt_username,
454                         fullname,
455                         homedir,
456                         dir_drive,
457                         logon_script,
458                         profile_path,
459                         acct_desc,
460                         munged_dial,
461                         workstations;
462         struct passwd   *pw;
463         uint32          user_rid, 
464                         group_rid;
465         uint8           smblmpwd[16],
466                         smbntpwd[16];
467         uint16          acct_ctrl, 
468                         logon_divs;
469         uint32 hours_len;
470         uint8           hours[MAX_HOURS_LEN];
471         pstring temp;
472         uid_t           uid = -1;
473         gid_t           gid = getegid();
474
475
476         /*
477          * do a little initialization
478          */
479         username[0]     = '\0';
480         domain[0]       = '\0';
481         nt_username[0]  = '\0';
482         fullname[0]     = '\0';
483         homedir[0]      = '\0';
484         dir_drive[0]    = '\0';
485         logon_script[0] = '\0';
486         profile_path[0] = '\0';
487         acct_desc[0]    = '\0';
488         munged_dial[0]  = '\0';
489         workstations[0] = '\0';
490          
491
492         if (sampass == NULL || ldap_struct == NULL || entry == NULL) {
493                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
494                 return False;
495         }
496
497         get_single_attribute(ldap_struct, entry, "uid", username);
498         DEBUG(2, ("Entry found for user: %s\n", username));
499
500         pstrcpy(nt_username, username);
501
502         pstrcpy(domain, lp_workgroup());
503
504         get_single_attribute(ldap_struct, entry, "rid", temp);
505         user_rid = (uint32)atol(temp);
506         if (!get_single_attribute(ldap_struct, entry, "primaryGroupID", temp)) {
507                 group_rid = 0;
508         } else {
509                 group_rid = (uint32)atol(temp);
510         }
511
512         if ((ldap_state->permit_non_unix_accounts) 
513             && (user_rid >= ldap_state->low_nua_rid)
514             && (user_rid <= ldap_state->high_nua_rid)) {
515                 
516         } else {
517                 
518                 /* These values MAY be in LDAP, but they can also be retrieved through 
519                  *  sys_getpw*() which is how we're doing it 
520                  */
521         
522                 pw = getpwnam_alloc(username);
523                 if (pw == NULL) {
524                         DEBUG (2,("init_sam_from_ldap: User [%s] does not have a uid!\n", username));
525                         return False;
526                 }
527                 uid = pw->pw_uid;
528                 gid = pw->pw_gid;
529
530                 passwd_free(&pw);
531
532                 pdb_set_uid(sampass, uid);
533                 pdb_set_gid(sampass, gid);
534
535                 if (group_rid == 0) {
536                         GROUP_MAP map;
537                         /* call the mapping code here */
538                         if(get_group_map_from_gid(gid, &map, MAPPING_WITHOUT_PRIV)) {
539                                 sid_peek_rid(&map.sid, &group_rid);
540                         } 
541                         else {
542                                 group_rid=pdb_gid_to_group_rid(gid);
543                         }
544                 }
545         }
546
547         if (!get_single_attribute(ldap_struct, entry, "pwdLastSet", temp)) {
548                 /* leave as default */
549         } else {
550                 pass_last_set_time = (time_t) atol(temp);
551                 pdb_set_pass_last_set_time(sampass, pass_last_set_time);
552         }
553
554         if (!get_single_attribute(ldap_struct, entry, "logonTime", temp)) {
555                 /* leave as default */
556         } else {
557                 logon_time = (time_t) atol(temp);
558                 pdb_set_logon_time(sampass, logon_time, True);
559         }
560
561         if (!get_single_attribute(ldap_struct, entry, "logoffTime", temp)) {
562                 /* leave as default */
563         } else {
564                 logoff_time = (time_t) atol(temp);
565                 pdb_set_logoff_time(sampass, logoff_time, True);
566         }
567
568         if (!get_single_attribute(ldap_struct, entry, "kickoffTime", temp)) {
569                 /* leave as default */
570         } else {
571                 kickoff_time = (time_t) atol(temp);
572                 pdb_set_kickoff_time(sampass, kickoff_time, True);
573         }
574
575         if (!get_single_attribute(ldap_struct, entry, "pwdCanChange", temp)) {
576                 /* leave as default */
577         } else {
578                 pass_can_change_time = (time_t) atol(temp);
579                 pdb_set_pass_can_change_time(sampass, pass_can_change_time, True);
580         }
581
582         if (!get_single_attribute(ldap_struct, entry, "pwdMustChange", temp)) {
583                 /* leave as default */
584         } else {
585                 pass_must_change_time = (time_t) atol(temp);
586                 pdb_set_pass_must_change_time(sampass, pass_must_change_time, True);
587         }
588
589         /* recommend that 'gecos' and 'displayName' should refer to the same
590          * attribute OID.  userFullName depreciated, only used by Samba
591          * primary rules of LDAP: don't make a new attribute when one is already defined
592          * that fits your needs; using cn then displayName rather than 'userFullName'
593          */
594
595         if (!get_single_attribute(ldap_struct, entry, "cn", fullname)) {
596                 if (!get_single_attribute(ldap_struct, entry, "displayName", fullname)) {
597                         /* leave as default */
598                 } else {
599                         pdb_set_fullname(sampass, fullname);
600                 }
601         } else {
602                 pdb_set_fullname(sampass, fullname);
603         }
604
605         if (!get_single_attribute(ldap_struct, entry, "homeDrive", dir_drive)) {
606                 pstrcpy(dir_drive, lp_logon_drive());
607                 standard_sub_advanced(-1, username, "", gid, username, dir_drive);
608                 DEBUG(5,("homeDrive fell back to %s\n",dir_drive));
609                 pdb_set_dir_drive(sampass, dir_drive, False);
610         } else {
611                 pdb_set_dir_drive(sampass, dir_drive, True);
612         }
613
614         if (!get_single_attribute(ldap_struct, entry, "smbHome", homedir)) {
615                 pstrcpy(homedir, lp_logon_home());
616                 standard_sub_advanced(-1, username, "", gid, username, homedir);
617                 DEBUG(5,("smbHome fell back to %s\n",homedir));
618                 pdb_set_homedir(sampass, homedir, False);
619         } else {
620                 pdb_set_homedir(sampass, homedir, True);
621         }
622
623         if (!get_single_attribute(ldap_struct, entry, "scriptPath", logon_script)) {
624                 pstrcpy(logon_script, lp_logon_script());
625                 standard_sub_advanced(-1, username, "", gid, username, logon_script);
626                 DEBUG(5,("scriptPath fell back to %s\n",logon_script));
627                 pdb_set_logon_script(sampass, logon_script, False);
628         } else {
629                 pdb_set_logon_script(sampass, logon_script, True);
630         }
631
632         if (!get_single_attribute(ldap_struct, entry, "profilePath", profile_path)) {
633                 pstrcpy(profile_path, lp_logon_path());
634                 standard_sub_advanced(-1, username, "", gid, username, profile_path);
635                 DEBUG(5,("profilePath fell back to %s\n",profile_path));
636                 pdb_set_profile_path(sampass, profile_path, False);
637         } else {
638                 pdb_set_profile_path(sampass, profile_path, True);
639         }
640
641         if (!get_single_attribute(ldap_struct, entry, "description", acct_desc)) {
642                 /* leave as default */
643         } else {
644                 pdb_set_acct_desc(sampass, acct_desc);
645         }
646
647         if (!get_single_attribute(ldap_struct, entry, "userWorkstations", workstations)) {
648                 /* leave as default */;
649         } else {
650                 pdb_set_workstations(sampass, workstations);
651         }
652
653         /* FIXME: hours stuff should be cleaner */
654         
655         logon_divs = 168;
656         hours_len = 21;
657         memset(hours, 0xff, hours_len);
658
659         if (!get_single_attribute (ldap_struct, entry, "lmPassword", temp)) {
660                 /* leave as default */
661         } else {
662                 pdb_gethexpwd(temp, smblmpwd);
663                 memset((char *)temp, '\0', sizeof(temp));
664                 if (!pdb_set_lanman_passwd(sampass, smblmpwd))
665                         return False;
666         }
667
668         if (!get_single_attribute (ldap_struct, entry, "ntPassword", temp)) {
669                 /* leave as default */
670         } else {
671                 pdb_gethexpwd(temp, smbntpwd);
672                 memset((char *)temp, '\0', sizeof(temp));
673                 if (!pdb_set_nt_passwd(sampass, smbntpwd))
674                         return False;
675         }
676
677         if (!get_single_attribute (ldap_struct, entry, "acctFlags", temp)) {
678                 acct_ctrl |= ACB_NORMAL;
679         } else {
680                 acct_ctrl = pdb_decode_acct_ctrl(temp);
681
682                 if (acct_ctrl == 0)
683                         acct_ctrl |= ACB_NORMAL;
684
685                 pdb_set_acct_ctrl(sampass, acct_ctrl);
686         }
687
688         pdb_set_hours_len(sampass, hours_len);
689         pdb_set_logon_divs(sampass, logon_divs);
690
691         pdb_set_user_rid(sampass, user_rid);
692         pdb_set_group_rid(sampass, group_rid);
693
694         pdb_set_username(sampass, username);
695
696         pdb_set_domain(sampass, domain);
697         pdb_set_nt_username(sampass, nt_username);
698
699         pdb_set_munged_dial(sampass, munged_dial);
700         
701         /* pdb_set_unknown_3(sampass, unknown3); */
702         /* pdb_set_unknown_5(sampass, unknown5); */
703         /* pdb_set_unknown_6(sampass, unknown6); */
704
705         pdb_set_hours(sampass, hours);
706
707         return True;
708 }
709
710 /**********************************************************************
711 Initialize SAM_ACCOUNT from an LDAP query
712 (Based on init_buffer_from_sam in pdb_tdb.c)
713 *********************************************************************/
714 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state, 
715                                 LDAPMod *** mods, int ldap_op, 
716                                 const SAM_ACCOUNT * sampass)
717 {
718         pstring temp;
719         uint32 rid;
720
721         if (mods == NULL || sampass == NULL) {
722                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
723                 return False;
724         }
725
726         *mods = NULL;
727
728         /* 
729          * took out adding "objectclass: sambaAccount"
730          * do this on a per-mod basis
731          */
732
733         make_a_mod(mods, ldap_op, "uid", pdb_get_username(sampass));
734         DEBUG(2, ("Setting entry for user: %s\n", pdb_get_username(sampass)));
735
736         if ( pdb_get_user_rid(sampass) ) {
737                 rid = pdb_get_user_rid(sampass);
738         } else if (IS_SAM_SET(sampass, FLAG_SAM_UID)) {
739                 rid = fallback_pdb_uid_to_user_rid(pdb_get_uid(sampass));
740         } else if (ldap_state->permit_non_unix_accounts) {
741                 rid = ldapsam_get_next_available_nua_rid(ldap_state);
742                 if (rid == 0) {
743                         DEBUG(0, ("NO user RID specified on account %s, and finding next available NUA RID failed, cannot store!\n", pdb_get_username(sampass)));
744                         return False;
745                 }
746         } else {
747                 DEBUG(0, ("NO user RID specified on account %s, cannot store!\n", pdb_get_username(sampass)));
748                 return False;
749         }
750
751         slprintf(temp, sizeof(temp) - 1, "%i", rid);
752         make_a_mod(mods, ldap_op, "rid", temp);
753
754         if ( pdb_get_group_rid(sampass) ) {
755                 rid = pdb_get_group_rid(sampass);
756         } else if (IS_SAM_SET(sampass, FLAG_SAM_GID)) {
757                 rid = pdb_gid_to_group_rid(pdb_get_gid(sampass));
758         } else if (ldap_state->permit_non_unix_accounts) {
759                 rid = DOMAIN_GROUP_RID_USERS;
760         } else {
761                 DEBUG(0, ("NO group RID specified on account %s, cannot store!\n", pdb_get_username(sampass)));
762                 return False;
763         }
764
765         slprintf(temp, sizeof(temp) - 1, "%i", rid);
766         make_a_mod(mods, ldap_op, "primaryGroupID", temp);
767
768         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
769         make_a_mod(mods, ldap_op, "pwdLastSet", temp);
770
771         /* displayName, cn, and gecos should all be the same
772            *  most easily accomplished by giving them the same OID
773            *  gecos isn't set here b/c it should be handled by the 
774            *  add-user script
775          */
776
777         make_a_mod(mods, ldap_op, "displayName", pdb_get_fullname(sampass));
778         make_a_mod(mods, ldap_op, "cn", pdb_get_fullname(sampass));
779         make_a_mod(mods, ldap_op, "description", pdb_get_acct_desc(sampass));
780         make_a_mod(mods, ldap_op, "userWorkstations", pdb_get_workstations(sampass));
781
782         /*
783          * Only updates fields which have been set (not defaults from smb.conf)
784          */
785
786         if (IS_SAM_SET(sampass, FLAG_SAM_SMBHOME))
787                 make_a_mod(mods, ldap_op, "smbHome", pdb_get_homedir(sampass));
788                 
789         if (IS_SAM_SET(sampass, FLAG_SAM_DRIVE))
790                 make_a_mod(mods, ldap_op, "homeDrive", pdb_get_dirdrive(sampass));
791         
792         if (IS_SAM_SET(sampass, FLAG_SAM_LOGONSCRIPT))
793                 make_a_mod(mods, ldap_op, "scriptPath", pdb_get_logon_script(sampass));
794
795         if (IS_SAM_SET(sampass, FLAG_SAM_PROFILE))
796                 make_a_mod(mods, ldap_op, "profilePath", pdb_get_profile_path(sampass));
797
798         if (IS_SAM_SET(sampass, FLAG_SAM_LOGONTIME)) {
799                 slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
800                 make_a_mod(mods, ldap_op, "logonTime", temp);
801         }
802
803         if (IS_SAM_SET(sampass, FLAG_SAM_LOGOFFTIME)) {
804                 slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
805                 make_a_mod(mods, ldap_op, "logoffTime", temp);
806         }
807
808         if (IS_SAM_SET(sampass, FLAG_SAM_KICKOFFTIME)) {
809                 slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
810                 make_a_mod(mods, ldap_op, "kickoffTime", temp);
811         }
812
813         if (IS_SAM_SET(sampass, FLAG_SAM_CANCHANGETIME)) {
814                 slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
815                 make_a_mod(mods, ldap_op, "pwdCanChange", temp);
816         }
817
818         if (IS_SAM_SET(sampass, FLAG_SAM_MUSTCHANGETIME)) {
819                 slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
820                 make_a_mod(mods, ldap_op, "pwdMustChange", temp);
821         }
822
823         /* FIXME: Hours stuff goes in LDAP  */
824         pdb_sethexpwd (temp, pdb_get_lanman_passwd(sampass), pdb_get_acct_ctrl(sampass));
825         make_a_mod (mods, ldap_op, "lmPassword", temp);
826         
827         pdb_sethexpwd (temp, pdb_get_nt_passwd(sampass), pdb_get_acct_ctrl(sampass));
828         make_a_mod (mods, ldap_op, "ntPassword", temp);
829         
830         make_a_mod (mods, ldap_op, "acctFlags", pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass),
831                 NEW_PW_FORMAT_SPACE_PADDED_LEN));
832
833         return True;
834 }
835
836
837 /**********************************************************************
838 Connect to LDAP server and find the next available RID.
839 *********************************************************************/
840 static uint32 check_nua_rid_is_avail(struct ldapsam_privates *ldap_state, uint32 top_rid, LDAP *ldap_struct) 
841 {
842         LDAPMessage *result;
843         uint32 final_rid = (top_rid & (~USER_RID_TYPE)) + RID_MULTIPLIER;
844         if (top_rid == 0) {
845                 return 0;
846         }
847         
848         if (final_rid < ldap_state->low_nua_rid || final_rid > ldap_state->high_nua_rid) {
849                 return 0;
850         }
851
852         if (ldapsam_search_one_user_by_rid(ldap_state, ldap_struct, final_rid, &result) != LDAP_SUCCESS) {
853                 DEBUG(0, ("Cannot allocate NUA RID %d (0x%x), as the confirmation search failed!\n", final_rid, final_rid));
854                 final_rid = 0;
855                 ldap_msgfree(result);
856         }
857
858         if (ldap_count_entries(ldap_struct, result) != 0)
859         {
860                 DEBUG(0, ("Cannot allocate NUA RID %d (0x%x), as the RID is already in use!!\n", final_rid, final_rid));
861                 final_rid = 0;
862                 ldap_msgfree(result);
863         }
864
865         DEBUG(5, ("NUA RID %d (0x%x), declared valid\n", final_rid, final_rid));
866         return final_rid;
867 }
868
869 /**********************************************************************
870 Extract the RID from an LDAP entry
871 *********************************************************************/
872 static uint32 entry_to_user_rid(struct ldapsam_privates *ldap_state, LDAPMessage *entry, LDAP *ldap_struct) {
873         uint32 rid;
874         SAM_ACCOUNT *user = NULL;
875         if (!NT_STATUS_IS_OK(pdb_init_sam(&user))) {
876                 return 0;
877         }
878
879         if (init_sam_from_ldap(ldap_state, user, ldap_struct, entry)) {
880                 rid = pdb_get_user_rid(user);
881         } else {
882                 rid =0;
883         }
884         pdb_free_sam(&user);
885         if (rid >= ldap_state->low_nua_rid && rid <= ldap_state->high_nua_rid) {
886                 return rid;
887         }
888         return 0;
889 }
890
891
892 /**********************************************************************
893 Connect to LDAP server and find the next available RID.
894 *********************************************************************/
895 static uint32 search_top_nua_rid(struct ldapsam_privates *ldap_state, LDAP *ldap_struct)
896 {
897         int rc;
898         pstring filter;
899         LDAPMessage *result;
900         LDAPMessage *entry;
901         char *final_filter = NULL;
902         uint32 top_rid = 0;
903         uint32 count;
904         uint32 rid;
905
906         pstrcpy(filter, lp_ldap_filter());
907         all_string_sub(filter, "%u", "*", sizeof(pstring));
908
909 #if 0
910         asprintf(&final_filter, "(&(%s)(&(rid>=%d)(rid<=%d)))", filter, ldap_state->low_nua_rid, ldap_state->high_nua_rid);
911 #else 
912         final_filter = strdup(filter);
913 #endif  
914         DEBUG(2, ("ldapsam_get_next_available_nua_rid: searching for:[%s]\n", final_filter));
915
916         rc = ldap_search_s(ldap_struct, lp_ldap_suffix(),
917                            LDAP_SCOPE_SUBTREE, final_filter, NULL, 0,
918                            &result);
919
920         if (rc != LDAP_SUCCESS)
921         {
922                 
923                 DEBUG(3, ("LDAP search failed! cannot find base for NUA RIDs: %s\n", ldap_err2string(rc)));
924                 DEBUGADD(3, ("Query was: %s, %s\n", lp_ldap_suffix(), final_filter));
925
926                 free(final_filter);
927                 ldap_msgfree(result);
928                 result = NULL;
929                 return 0;
930         }
931         
932         count = ldap_count_entries(ldap_struct, result);
933         DEBUG(2, ("search_top_nua_rid: %d entries in the base!\n", count));
934         
935         if (count == 0) {
936                 DEBUG(3, ("LDAP search returned no records, assuming no non-unix-accounts present!: %s\n", ldap_err2string(rc)));
937                 DEBUGADD(3, ("Query was: %s, %s\n", lp_ldap_suffix(), final_filter));
938                 free(final_filter);
939                 ldap_msgfree(result);
940                 result = NULL;
941                 return ldap_state->low_nua_rid;
942         }
943         
944         free(final_filter);
945         entry = ldap_first_entry(ldap_struct,result);
946
947         top_rid = entry_to_user_rid(ldap_state, entry, ldap_struct);
948
949         while ((entry = ldap_next_entry(ldap_struct, entry))) {
950
951                 rid = entry_to_user_rid(ldap_state, entry, ldap_struct);
952                 if (rid > top_rid) {
953                         top_rid = rid;
954                 }
955         }
956
957         ldap_msgfree(result);
958         return top_rid;
959 }
960
961 /**********************************************************************
962 Connect to LDAP server and find the next available RID.
963 *********************************************************************/
964 static uint32 ldapsam_get_next_available_nua_rid(struct ldapsam_privates *ldap_state) {
965         LDAP *ldap_struct;
966         uint32 next_nua_rid;
967         uint32 top_nua_rid;
968
969         if (!ldapsam_open_connection(ldap_state, &ldap_struct))
970         {
971                 return 0;
972         }
973         if (!ldapsam_connect_system(ldap_state, ldap_struct))
974         {
975                 ldap_unbind(ldap_struct);
976                 return 0;
977         }
978         
979         top_nua_rid = search_top_nua_rid(ldap_state, ldap_struct);
980
981         next_nua_rid = check_nua_rid_is_avail(ldap_state, 
982                                               top_nua_rid, ldap_struct);
983         
984         ldap_unbind(ldap_struct);
985         return next_nua_rid;
986 }
987
988 /**********************************************************************
989 Connect to LDAP server for password enumeration
990 *********************************************************************/
991 static BOOL ldapsam_setsampwent(struct pdb_methods *my_methods, BOOL update)
992 {
993         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
994         int rc;
995         pstring filter;
996
997         if (!ldapsam_open_connection(ldap_state, &ldap_state->ldap_struct))
998         {
999                 return False;
1000         }
1001         if (!ldapsam_connect_system(ldap_state, ldap_state->ldap_struct))
1002         {
1003                 ldap_unbind(ldap_state->ldap_struct);
1004                 return False;
1005         }
1006
1007         pstrcpy(filter, lp_ldap_filter());
1008         all_string_sub(filter, "%u", "*", sizeof(pstring));
1009
1010         rc = ldap_search_s(ldap_state->ldap_struct, lp_ldap_suffix(),
1011                            LDAP_SCOPE_SUBTREE, filter, NULL, 0,
1012                            &ldap_state->result);
1013
1014         if (rc != LDAP_SUCCESS)
1015         {
1016                 DEBUG(0, ("LDAP search failed: %s\n", ldap_err2string(rc)));
1017                 DEBUG(3, ("Query was: %s, %s\n", lp_ldap_suffix(), filter));
1018                 ldap_msgfree(ldap_state->result);
1019                 ldap_unbind(ldap_state->ldap_struct);
1020                 ldap_state->ldap_struct = NULL;
1021                 ldap_state->result = NULL;
1022                 return False;
1023         }
1024
1025         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base!\n",
1026                 ldap_count_entries(ldap_state->ldap_struct,
1027                 ldap_state->result)));
1028
1029         ldap_state->entry = ldap_first_entry(ldap_state->ldap_struct,
1030                                  ldap_state->result);
1031         ldap_state->index = 0;
1032
1033         return True;
1034 }
1035
1036 /**********************************************************************
1037 End enumeration of the LDAP password list 
1038 *********************************************************************/
1039 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1040 {
1041         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1042         if (ldap_state->ldap_struct && ldap_state->result)
1043         {
1044                 ldap_msgfree(ldap_state->result);
1045                 ldap_unbind(ldap_state->ldap_struct);
1046                 ldap_state->ldap_struct = NULL;
1047                 ldap_state->result = NULL;
1048         }
1049 }
1050
1051 /**********************************************************************
1052 Get the next entry in the LDAP password database 
1053 *********************************************************************/
1054 static BOOL ldapsam_getsampwent(struct pdb_methods *my_methods, SAM_ACCOUNT * user)
1055 {
1056         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1057         BOOL ret = False;
1058
1059         while (!ret) {
1060                 if (!ldap_state->entry)
1061                         return False;
1062                 
1063                 ldap_state->index++;
1064                 ret = init_sam_from_ldap(ldap_state, user, ldap_state->ldap_struct,
1065                                          ldap_state->entry);
1066                 
1067                 ldap_state->entry = ldap_next_entry(ldap_state->ldap_struct,
1068                                             ldap_state->entry);
1069                 
1070         }
1071
1072         return True;
1073 }
1074
1075 /**********************************************************************
1076 Get SAM_ACCOUNT entry from LDAP by username 
1077 *********************************************************************/
1078 static BOOL ldapsam_getsampwnam(struct pdb_methods *my_methods, SAM_ACCOUNT * user, const char *sname)
1079 {
1080         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1081         LDAP *ldap_struct;
1082         LDAPMessage *result;
1083         LDAPMessage *entry;
1084
1085         if (!ldapsam_open_connection(ldap_state, &ldap_struct))
1086                 return False;
1087         if (!ldapsam_connect_system(ldap_state, ldap_struct))
1088         {
1089                 ldap_unbind(ldap_struct);
1090                 return False;
1091         }
1092         if (ldapsam_search_one_user_by_name(ldap_state, ldap_struct, sname, &result) != LDAP_SUCCESS)
1093         {
1094                 ldap_unbind(ldap_struct);
1095                 return False;
1096         }
1097         if (ldap_count_entries(ldap_struct, result) < 1)
1098         {
1099                 DEBUG(4,
1100                       ("We didn't find the user [%s] count=%d\n", sname,
1101                        ldap_count_entries(ldap_struct, result)));
1102                 ldap_unbind(ldap_struct);
1103                 return False;
1104         }
1105         entry = ldap_first_entry(ldap_struct, result);
1106         if (entry)
1107         {
1108                 if (!init_sam_from_ldap(ldap_state, user, ldap_struct, entry)) {
1109                         DEBUG(0,("ldapsam_getsampwnam: init_sam_from_ldap failed!\n"));
1110                         ldap_msgfree(result);
1111                         ldap_unbind(ldap_struct);
1112                         return False;
1113                 }
1114                 ldap_msgfree(result);
1115                 ldap_unbind(ldap_struct);
1116                 return True;
1117         }
1118         else
1119         {
1120                 ldap_msgfree(result);
1121                 ldap_unbind(ldap_struct);
1122                 return False;
1123         }
1124 }
1125
1126 /**********************************************************************
1127 Get SAM_ACCOUNT entry from LDAP by rid 
1128 *********************************************************************/
1129 static BOOL ldapsam_getsampwrid(struct pdb_methods *my_methods, SAM_ACCOUNT * user, uint32 rid)
1130 {
1131         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1132         LDAP *ldap_struct;
1133         LDAPMessage *result;
1134         LDAPMessage *entry;
1135
1136         if (!ldapsam_open_connection(ldap_state, &ldap_struct))
1137                 return False;
1138
1139         if (!ldapsam_connect_system(ldap_state, ldap_struct))
1140         {
1141                 ldap_unbind(ldap_struct);
1142                 return False;
1143         }
1144         if (ldapsam_search_one_user_by_rid(ldap_state, ldap_struct, rid, &result) !=
1145             LDAP_SUCCESS)
1146         {
1147                 ldap_unbind(ldap_struct);
1148                 return False;
1149         }
1150
1151         if (ldap_count_entries(ldap_struct, result) < 1)
1152         {
1153                 DEBUG(0,
1154                       ("We didn't find the rid [%i] count=%d\n", rid,
1155                        ldap_count_entries(ldap_struct, result)));
1156                 ldap_unbind(ldap_struct);
1157                 return False;
1158         }
1159
1160         entry = ldap_first_entry(ldap_struct, result);
1161         if (entry)
1162         {
1163                 if (!init_sam_from_ldap(ldap_state, user, ldap_struct, entry)) {
1164                         DEBUG(0,("ldapsam_getsampwrid: init_sam_from_ldap failed!\n"));
1165                         ldap_msgfree(result);
1166                         ldap_unbind(ldap_struct);
1167                         return False;
1168                 }
1169                 ldap_msgfree(result);
1170                 ldap_unbind(ldap_struct);
1171                 return True;
1172         }
1173         else
1174         {
1175                 ldap_msgfree(result);
1176                 ldap_unbind(ldap_struct);
1177                 return False;
1178         }
1179 }
1180
1181 /**********************************************************************
1182 Delete entry from LDAP for username 
1183 *********************************************************************/
1184 static BOOL ldapsam_delete_sam_account(struct pdb_methods *my_methods, const SAM_ACCOUNT * sam_acct)
1185 {
1186         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1187         const char *sname;
1188         int rc;
1189         char *dn;
1190         LDAP *ldap_struct;
1191         LDAPMessage *entry;
1192         LDAPMessage *result;
1193
1194         if (!sam_acct) {
1195                 DEBUG(0, ("sam_acct was NULL!\n"));
1196                 return False;
1197         }
1198
1199         sname = pdb_get_username(sam_acct);
1200
1201         if (!ldapsam_open_connection(ldap_state, &ldap_struct))
1202                 return False;
1203
1204         DEBUG (3, ("Deleting user %s from LDAP.\n", sname));
1205         
1206         if (!ldapsam_connect_system(ldap_state, ldap_struct)) {
1207                 ldap_unbind (ldap_struct);
1208                 DEBUG(0, ("failed to delete user %s from the LDAP database.\n", sname));
1209                 return False;
1210         }
1211
1212         rc = ldapsam_search_one_user_by_name(ldap_state, ldap_struct, sname, &result);
1213         if (ldap_count_entries (ldap_struct, result) == 0) {
1214                 DEBUG (0, ("User doesn't exit!\n"));
1215                 ldap_msgfree (result);
1216                 ldap_unbind (ldap_struct);
1217                 return False;
1218         }
1219
1220         entry = ldap_first_entry (ldap_struct, result);
1221         dn = ldap_get_dn (ldap_struct, entry);
1222
1223         rc = ldap_delete_s (ldap_struct, dn);
1224
1225         ldap_memfree (dn);
1226         if (rc != LDAP_SUCCESS) {
1227                 char *ld_error;
1228                 ldap_get_option (ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
1229                 DEBUG (0,("failed to delete user with uid = %s with: %s\n\t%s\n",
1230                         sname, ldap_err2string (rc), ld_error));
1231                 free (ld_error);
1232                 ldap_unbind (ldap_struct);
1233                 return False;
1234         }
1235
1236         DEBUG (2,("successfully deleted uid = %s from the LDAP database\n", sname));
1237         ldap_unbind (ldap_struct);
1238         return True;
1239 }
1240
1241 /**********************************************************************
1242 Update SAM_ACCOUNT 
1243 *********************************************************************/
1244 static BOOL ldapsam_update_sam_account(struct pdb_methods *my_methods, const SAM_ACCOUNT * newpwd)
1245 {
1246         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1247         int rc;
1248         char *dn;
1249         LDAP *ldap_struct;
1250         LDAPMessage *result;
1251         LDAPMessage *entry;
1252         LDAPMod **mods;
1253
1254         if (!ldapsam_open_connection(ldap_state, &ldap_struct)) /* open a connection to the server */
1255                 return False;
1256
1257         if (!ldapsam_connect_system(ldap_state, ldap_struct))   /* connect as system account */
1258         {
1259                 ldap_unbind(ldap_struct);
1260                 return False;
1261         }
1262
1263         rc = ldapsam_search_one_user_by_name(ldap_state, ldap_struct,
1264                                              pdb_get_username(newpwd), &result);
1265
1266         if (ldap_count_entries(ldap_struct, result) == 0)
1267         {
1268                 DEBUG(0, ("No user to modify!\n"));
1269                 ldap_msgfree(result);
1270                 ldap_unbind(ldap_struct);
1271                 return False;
1272         }
1273
1274         if (!init_ldap_from_sam(ldap_state, &mods, LDAP_MOD_REPLACE, newpwd)) {
1275                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1276                 ldap_msgfree(result);
1277                 ldap_unbind(ldap_struct);
1278                 return False;
1279         }
1280
1281         entry = ldap_first_entry(ldap_struct, result);
1282         dn = ldap_get_dn(ldap_struct, entry);
1283
1284         rc = ldap_modify_s(ldap_struct, dn, mods);
1285
1286         if (rc != LDAP_SUCCESS)
1287         {
1288                 char *ld_error;
1289                 ldap_get_option(ldap_struct, LDAP_OPT_ERROR_STRING,
1290                                 &ld_error);
1291                 DEBUG(0,
1292                       ("failed to modify user with uid = %s with: %s\n\t%s\n",
1293                        pdb_get_username(newpwd), ldap_err2string(rc),
1294                        ld_error));
1295                 free(ld_error);
1296                 ldap_unbind(ldap_struct);
1297                 return False;
1298         }
1299
1300         DEBUG(2,
1301               ("successfully modified uid = %s in the LDAP database\n",
1302                pdb_get_username(newpwd)));
1303         ldap_mods_free(mods, 1);
1304         ldap_unbind(ldap_struct);
1305         return True;
1306 }
1307
1308 /**********************************************************************
1309 Add SAM_ACCOUNT to LDAP 
1310 *********************************************************************/
1311 static BOOL ldapsam_add_sam_account(struct pdb_methods *my_methods, const SAM_ACCOUNT * newpwd)
1312 {
1313         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1314         int rc;
1315         pstring filter;
1316         LDAP *ldap_struct = NULL;
1317         LDAPMessage *result = NULL;
1318         pstring dn;
1319         LDAPMod **mods = NULL;
1320         int             ldap_op;
1321         uint32          num_result;
1322
1323         const char *username = pdb_get_username(newpwd);
1324         if (!username || !*username) {
1325                 DEBUG(0, ("Cannot add user without a username!\n"));
1326                 return False;
1327         }
1328
1329         if (!ldapsam_open_connection(ldap_state, &ldap_struct)) /* open a connection to the server */
1330         {
1331                 return False;
1332         }
1333
1334         if (!ldapsam_connect_system(ldap_state, ldap_struct))   /* connect as system account */
1335         {
1336                 ldap_unbind(ldap_struct);
1337                 return False;
1338         }
1339
1340         rc = ldapsam_search_one_user_by_name (ldap_state, ldap_struct, username, &result);
1341
1342         if (ldap_count_entries(ldap_struct, result) != 0)
1343         {
1344                 DEBUG(0,("User already in the base, with samba properties\n"));
1345                 ldap_msgfree(result);
1346                 ldap_unbind(ldap_struct);
1347                 return False;
1348         }
1349         ldap_msgfree(result);
1350
1351         slprintf (filter, sizeof (filter) - 1, "uid=%s", username);
1352         rc = ldapsam_search_one_user(ldap_state, ldap_struct, filter, &result);
1353         num_result = ldap_count_entries(ldap_struct, result);
1354         
1355         if (num_result > 1) {
1356                 DEBUG (0, ("More than one user with that uid exists: bailing out!\n"));
1357                 ldap_msgfree(result);
1358                 return False;
1359         }
1360         
1361         /* Check if we need to update an existing entry */
1362         if (num_result == 1) {
1363                 char *tmp;
1364                 LDAPMessage *entry;
1365                 
1366                 DEBUG(3,("User exists without samba properties: adding them\n"));
1367                 ldap_op = LDAP_MOD_REPLACE;
1368                 entry = ldap_first_entry (ldap_struct, result);
1369                 tmp = ldap_get_dn (ldap_struct, entry);
1370                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1371                 ldap_memfree (tmp);
1372         }
1373         else {
1374                 /* Check if we need to add an entry */
1375                 DEBUG(3,("Adding new user\n"));
1376                 ldap_op = LDAP_MOD_ADD;
1377                 if (username[strlen(username)-1] == '$') {
1378                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_machine_suffix ());
1379                 } else {
1380                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_user_suffix ());
1381                 }
1382         }
1383
1384         ldap_msgfree(result);
1385
1386         if (!init_ldap_from_sam(ldap_state, &mods, ldap_op, newpwd)) {
1387                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
1388                 ldap_mods_free(mods, 1);
1389                 ldap_unbind(ldap_struct);
1390                 return False;           
1391         }
1392         make_a_mod(&mods, LDAP_MOD_ADD, "objectclass", "sambaAccount");
1393
1394         if (ldap_op == LDAP_MOD_REPLACE) {
1395                 rc = ldap_modify_s(ldap_struct, dn, mods);
1396         }
1397         else {
1398                 rc = ldap_add_s(ldap_struct, dn, mods);
1399         }
1400
1401         if (rc != LDAP_SUCCESS)
1402         {
1403                 char *ld_error;
1404
1405                 ldap_get_option (ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
1406                 DEBUG(0,("failed to modify/add user with uid = %s (dn = %s) with: %s\n\t%s\n",
1407                         pdb_get_username(newpwd), dn, ldap_err2string (rc), ld_error));
1408                 free(ld_error);
1409                 ldap_mods_free(mods, 1);
1410                 ldap_unbind(ldap_struct);
1411                 return False;
1412         }
1413         
1414         DEBUG(2,("added: uid = %s in the LDAP database\n", pdb_get_username(newpwd)));
1415         ldap_mods_free(mods, 1);
1416         ldap_unbind(ldap_struct);
1417         return True;
1418 }
1419
1420 static void free_private_data(void **vp) 
1421 {
1422         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
1423
1424         if ((*ldap_state)->ldap_struct) {
1425                 ldap_unbind((*ldap_state)->ldap_struct);
1426         }
1427
1428         *ldap_state = NULL;
1429
1430         /* No need to free any further, as it is talloc()ed */
1431 }
1432
1433 NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
1434 {
1435         NTSTATUS nt_status;
1436         struct ldapsam_privates *ldap_state;
1437
1438         if (!NT_STATUS_IS_OK(nt_status = make_pdb_methods(pdb_context->mem_ctx, pdb_method))) {
1439                 return nt_status;
1440         }
1441
1442         (*pdb_method)->name = "ldapsam";
1443
1444         (*pdb_method)->setsampwent = ldapsam_setsampwent;
1445         (*pdb_method)->endsampwent = ldapsam_endsampwent;
1446         (*pdb_method)->getsampwent = ldapsam_getsampwent;
1447         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
1448         (*pdb_method)->getsampwrid = ldapsam_getsampwrid;
1449         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
1450         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
1451         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
1452
1453         /* TODO: Setup private data and free */
1454
1455         ldap_state = talloc_zero(pdb_context->mem_ctx, sizeof(struct ldapsam_privates));
1456
1457         if (!ldap_state) {
1458                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1459                 return NT_STATUS_NO_MEMORY;
1460         }
1461
1462         if (location) {
1463                 ldap_state->uri = talloc_strdup(pdb_context->mem_ctx, location);
1464         } else {
1465                 ldap_state->uri = "ldap://localhost";
1466         }
1467
1468         (*pdb_method)->private_data = ldap_state;
1469
1470         (*pdb_method)->free_private_data = free_private_data;
1471
1472         return NT_STATUS_OK;
1473 }
1474
1475 NTSTATUS pdb_init_ldapsam_nua(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
1476 {
1477         NTSTATUS nt_status;
1478         struct ldapsam_privates *ldap_state;
1479         uint32 low_nua_uid, high_nua_uid;
1480
1481         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam(pdb_context, pdb_method, location))) {
1482                 return nt_status;
1483         }
1484
1485         (*pdb_method)->name = "ldapsam_nua";
1486
1487         ldap_state = (*pdb_method)->private_data;
1488         
1489         ldap_state->permit_non_unix_accounts = True;
1490
1491         if (!lp_non_unix_account_range(&low_nua_uid, &high_nua_uid)) {
1492                 DEBUG(0, ("cannot use ldapsam_nua without 'non unix account range' in smb.conf!\n"));
1493                 return NT_STATUS_UNSUCCESSFUL;
1494         }
1495
1496         ldap_state->low_nua_rid=fallback_pdb_uid_to_user_rid(low_nua_uid);
1497
1498         ldap_state->high_nua_rid=fallback_pdb_uid_to_user_rid(high_nua_uid);
1499
1500         return NT_STATUS_OK;
1501 }
1502
1503
1504 #else
1505
1506 NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
1507 {
1508         DEBUG(0, ("ldapsam not compiled in!\n"));
1509         return NT_STATUS_UNSUCCESSFUL;
1510 }
1511
1512 NTSTATUS pdb_init_ldapsam_nua(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
1513 {
1514         DEBUG(0, ("ldapsam_nua not compiled in!\n"));
1515         return NT_STATUS_UNSUCCESSFUL;
1516 }
1517
1518
1519 #endif