b8ec37814d99ec6e8a65a783b8972633390e9dab
[jpeach/samba.git] / source / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 2.9.
4    LDAP protocol helper functions for SAMBA
5    Copyright (C) Gerald Carter 2001
6    Copyright (C) Shahms King 2001
7    Copyright (C) Jean François Micouleau 1998
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 ldap_enum_info {
56         LDAP *ldap_struct;
57         LDAPMessage *result;
58         LDAPMessage *entry;
59 };
60
61 static struct ldap_enum_info global_ldap_ent;
62
63
64
65 /*******************************************************************
66  open a connection to the ldap server.
67 ******************************************************************/
68 static BOOL ldap_open_connection (LDAP ** ldap_struct)
69 {
70         int port;
71         int version, rc;
72         int tls = LDAP_OPT_X_TLS_HARD;
73
74         /* there should be an lp_ldap_ssl_port(), what happen if for some
75            reason we need to bind an SSLed LDAP on port 389 ?? ---simo */
76         if (lp_ldap_ssl() == LDAP_SSL_ON && lp_ldap_port() == 389) {
77                 port = 636;
78         }
79         else {
80                 port = lp_ldap_port();
81         }
82
83         if ((*ldap_struct = ldap_init(lp_ldap_server(), port)) == NULL) {
84                 DEBUG(0, ("The LDAP server is not responding !\n"));
85                 return False;
86         }
87
88         /* Connect to older servers using SSL and V2 rather than Start TLS */
89         if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
90         {
91                 if (version != LDAP_VERSION2)
92                 {
93                         version = LDAP_VERSION2;
94                         ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
95                 }
96         }
97
98         switch (lp_ldap_ssl())
99         {
100                 case LDAP_SSL_START_TLS:
101                         if (ldap_get_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, 
102                                 &version) == LDAP_OPT_SUCCESS)
103                         {
104                                 if (version < LDAP_VERSION3)
105                                 {
106                                         version = LDAP_VERSION3;
107                                         ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION,
108                                                         &version);
109                                 }
110                         }
111                         if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
112                         {
113                                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
114                                        ldap_err2string(rc)));
115                                 return False;
116                         }
117                         DEBUG (2, ("StartTLS issued: using a TLS connection\n"));
118                         break;
119                         
120                 case LDAP_SSL_ON:
121                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
122                         {
123                                 DEBUG(0, ("Failed to setup a TLS session\n"));
124                         }
125                         break;
126                         
127                 case LDAP_SSL_OFF:
128                 default:
129                         /* 
130                          * No special needs to setup options prior to the LDAP
131                          * bind (which should be called next via ldap_connect_system()
132                          */
133                         break;
134         }
135
136         DEBUG(2, ("ldap_open_connection: connection opened\n"));
137         return True;
138 }
139
140 /*******************************************************************
141  connect to the ldap server under system privilege.
142 ******************************************************************/
143 static BOOL ldap_connect_system(LDAP * ldap_struct)
144 {
145         int rc;
146         static BOOL got_pw = False;
147         static pstring ldap_secret;
148
149         /* get the password if we don't have it already */
150         if (!got_pw && !(got_pw=fetch_ldap_pw(lp_ldap_admin_dn(), ldap_secret, sizeof(pstring)))) 
151         {
152                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password for %s from secrets.tdb\n",
153                         lp_ldap_admin_dn()));
154                 return False;
155         }
156
157         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
158            (OpenLDAP) doesnt' seem to support it */
159            
160         DEBUG(10,("ldap_connect_system: Binding to ldap server as \"%s\"\n",
161                 lp_ldap_admin_dn()));
162                 
163         if ((rc = ldap_simple_bind_s(ldap_struct, lp_ldap_admin_dn(), 
164                 ldap_secret)) != LDAP_SUCCESS)
165         {
166                 DEBUG(0, ("Bind failed: %s\n", ldap_err2string(rc)));
167                 return False;
168         }
169         
170         DEBUG(2, ("ldap_connect_system: succesful connection to the LDAP server\n"));
171         return True;
172 }
173
174 /*******************************************************************
175  run the search by name.
176 ******************************************************************/
177 static int ldap_search_one_user (LDAP * ldap_struct, const char *filter, LDAPMessage ** result)
178 {
179         int scope = LDAP_SCOPE_SUBTREE;
180         int rc;
181
182         DEBUG(2, ("ldap_search_one_user: searching for:[%s]\n", filter));
183
184         rc = ldap_search_s(ldap_struct, lp_ldap_suffix (), scope, filter, NULL, 0, result);
185
186         if (rc != LDAP_SUCCESS) {
187                 DEBUG(0,("ldap_search_one_user: Problem during the LDAP search: %s\n", 
188                         ldap_err2string (rc)));
189                 DEBUG(3,("ldap_search_one_user: Query was: %s, %s\n", lp_ldap_suffix(), 
190                         filter));
191         }
192         
193         return rc;
194 }
195
196 /*******************************************************************
197  run the search by name.
198 ******************************************************************/
199 static int ldap_search_one_user_by_name (LDAP * ldap_struct, const char *user,
200                              LDAPMessage ** result)
201 {
202         pstring filter;
203         
204         /*
205          * in the filter expression, replace %u with the real name
206          * so in ldap filter, %u MUST exist :-)
207          */
208         pstrcpy(filter, lp_ldap_filter());
209
210         /* 
211          * have to use this here because $ is filtered out
212            * in pstring_sub
213          */
214         all_string_sub(filter, "%u", user, sizeof(pstring));
215
216         return ldap_search_one_user(ldap_struct, filter, result);
217 }
218
219 /*******************************************************************
220  run the search by uid.
221 ******************************************************************/
222 static int ldap_search_one_user_by_uid(LDAP * ldap_struct, int uid,
223                             LDAPMessage ** result)
224 {
225         struct passwd *user;
226         pstring filter;
227
228         /* Get the username from the system and look that up in the LDAP */
229         
230         if ((user = sys_getpwuid(uid)) == NULL) {
231                 DEBUG(3,("ldap_search_one_user_by_uid: Failed to locate uid [%d]\n", uid));
232                 return LDAP_NO_SUCH_OBJECT;
233         }
234         
235         pstrcpy(filter, lp_ldap_filter());
236         
237         all_string_sub(filter, "%u", user->pw_name, sizeof(pstring));
238
239         return ldap_search_one_user(ldap_struct, filter, result);
240 }
241
242 /*******************************************************************
243  run the search by rid.
244 ******************************************************************/
245 static int ldap_search_one_user_by_rid (LDAP * ldap_struct, uint32 rid,
246                             LDAPMessage ** result)
247 {
248         pstring filter;
249         int rc;
250
251         /* check if the user rid exsists, if not, try searching on the uid */
252         
253         snprintf(filter, sizeof(filter) - 1, "rid=%i", rid);
254         rc = ldap_search_one_user(ldap_struct, filter, result);
255         
256         if (rc != LDAP_SUCCESS)
257                 rc = ldap_search_one_user_by_uid(ldap_struct, 
258                         pdb_user_rid_to_uid(rid), result);
259
260         return rc;
261 }
262
263 /*******************************************************************
264 search an attribute and return the first value found.
265 ******************************************************************/
266 static BOOL get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
267                      char *attribute, char *value)
268 {
269         char **values;
270
271         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
272                 value = NULL;
273                 DEBUG (2, ("get_single_attribute: [%s] = [<does not exist>]\n", attribute));
274                 
275                 return False;
276         }
277
278         pstrcpy(value, values[0]);
279         ldap_value_free(values);
280         DEBUG (2, ("get_single_attribute: [%s] = [%s]\n", attribute, value));
281                 
282         return True;
283 }
284
285 /************************************************************************
286 Routine to manage the LDAPMod structure array
287 manage memory used by the array, by each struct, and values
288
289 ************************************************************************/
290 static void make_a_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
291 {
292         LDAPMod **mods;
293         int i;
294         int j;
295
296         mods = *modlist;
297
298         if (attribute == NULL || *attribute == '\0')
299                 return;
300
301         if (value == NULL || *value == '\0')
302                 return;
303
304         if (mods == NULL) 
305         {
306                 mods = (LDAPMod **) malloc(sizeof(LDAPMod *));
307                 if (mods == NULL)
308                 {
309                         DEBUG(0, ("make_a_mod: out of memory!\n"));
310                         return;
311                 }
312                 mods[0] = NULL;
313         }
314
315         for (i = 0; mods[i] != NULL; ++i) {
316                 if (mods[i]->mod_op == modop && !strcasecmp(mods[i]->mod_type, attribute))
317                         break;
318         }
319
320         if (mods[i] == NULL)
321         {
322                 mods = (LDAPMod **) Realloc (mods, (i + 2) * sizeof (LDAPMod *));
323                 if (mods == NULL)
324                 {
325                         DEBUG(0, ("make_a_mod: out of memory!\n"));
326                         return;
327                 }
328                 mods[i] = (LDAPMod *) malloc(sizeof(LDAPMod));
329                 if (mods[i] == NULL)
330                 {
331                         DEBUG(0, ("make_a_mod: out of memory!\n"));
332                         return;
333                 }
334                 mods[i]->mod_op = modop;
335                 mods[i]->mod_values = NULL;
336                 mods[i]->mod_type = strdup(attribute);
337                 mods[i + 1] = NULL;
338         }
339
340         if (value != NULL)
341         {
342                 j = 0;
343                 if (mods[i]->mod_values != NULL) {
344                         for (; mods[i]->mod_values[j] != NULL; j++);
345                 }
346                 mods[i]->mod_values = (char **)Realloc(mods[i]->mod_values,
347                                                (j + 2) * sizeof (char *));
348                                                
349                 if (mods[i]->mod_values == NULL) {
350                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
351                         return;
352                 }
353                 mods[i]->mod_values[j] = strdup(value);
354                 mods[i]->mod_values[j + 1] = NULL;
355         }
356         *modlist = mods;
357 }
358
359 /* New Interface is being implemented here */
360
361 /**********************************************************************
362 Initialize SAM_ACCOUNT from an LDAP query
363 (Based on init_sam_from_buffer in pdb_tdb.c)
364 *********************************************************************/
365 static BOOL init_sam_from_ldap (SAM_ACCOUNT * sampass,
366                    LDAP * ldap_struct, LDAPMessage * entry)
367 {
368         time_t  logon_time,
369                         logoff_time,
370                         kickoff_time,
371                         pass_last_set_time, 
372                         pass_can_change_time, 
373                         pass_must_change_time;
374         pstring         username, 
375                         domain,
376                         nt_username,
377                         fullname,
378                         homedir,
379                         dir_drive,
380                         logon_script,
381                         profile_path,
382                         acct_desc,
383                         munged_dial,
384                         workstations;
385         struct passwd   *pw;
386         uint32          user_rid, 
387                         group_rid;
388         uint8           smblmpwd[16],
389                         smbntpwd[16];
390         uint16          acct_ctrl, 
391                         logon_divs;
392         uint32 hours_len;
393         uint8           hours[MAX_HOURS_LEN];
394         pstring temp;
395         uid_t           uid = -1;
396         gid_t           gid = getegid();
397
398
399         /*
400          * do a little initialization
401          */
402         username[0]     = '\0';
403         domain[0]       = '\0';
404         nt_username[0]  = '\0';
405         fullname[0]     = '\0';
406         homedir[0]      = '\0';
407         dir_drive[0]    = '\0';
408         logon_script[0] = '\0';
409         profile_path[0] = '\0';
410         acct_desc[0]    = '\0';
411         munged_dial[0]  = '\0';
412         workstations[0] = '\0';
413          
414
415         if (sampass == NULL || ldap_struct == NULL || entry == NULL) {
416                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
417                 return False;
418         }
419
420         get_single_attribute(ldap_struct, entry, "uid", username);
421         DEBUG(2, ("Entry found for user: %s\n", username));
422
423         pstrcpy(nt_username, username);
424
425         pstrcpy(domain, lp_workgroup());
426
427         get_single_attribute(ldap_struct, entry, "pwdLastSet", temp);
428         pass_last_set_time = (time_t) strtol(temp, NULL, 16);
429
430         get_single_attribute(ldap_struct, entry, "logonTime", temp);
431         logon_time = (time_t) strtol(temp, NULL, 16);
432
433         get_single_attribute(ldap_struct, entry, "logoffTime", temp);
434         logoff_time = (time_t) strtol(temp, NULL, 16);
435
436         get_single_attribute(ldap_struct, entry, "kickoffTime", temp);
437         kickoff_time = (time_t) strtol(temp, NULL, 16);
438
439         get_single_attribute(ldap_struct, entry, "pwdCanChange", temp);
440         pass_can_change_time = (time_t) strtol(temp, NULL, 16);
441
442         get_single_attribute(ldap_struct, entry, "pwdMustChange", temp);
443         pass_must_change_time = (time_t) strtol(temp, NULL, 16);
444
445         /* recommend that 'gecos' and 'displayName' should refer to the same
446            * attribute OID.  userFullName depreciated, only used by Samba
447            * primary rules of LDAP: don't make a new attribute when one is already defined
448          * that fits your needs; using cn then displayName rather than 'userFullName'
449          */
450
451         if (!get_single_attribute(ldap_struct, entry, "cn", fullname)) {
452                 get_single_attribute(ldap_struct, entry, "displayName", fullname);
453         }
454
455
456         if (!get_single_attribute(ldap_struct, entry, "homeDrive", dir_drive)) {
457                 pstrcpy(dir_drive, lp_logon_drive());
458                 standard_sub_advanced(-1, username, "", gid, username, dir_drive);
459                 DEBUG(5,("homeDrive fell back to %s\n",dir_drive));
460                 pdb_set_dir_drive(sampass, dir_drive, False);
461         }
462         else
463                 pdb_set_dir_drive(sampass, dir_drive, True);
464
465         if (!get_single_attribute(ldap_struct, entry, "smbHome", homedir)) {
466                 pstrcpy(homedir, lp_logon_home());
467                 standard_sub_advanced(-1, username, "", gid, username, homedir);
468                 DEBUG(5,("smbHome fell back to %s\n",homedir));
469                 pdb_set_homedir(sampass, homedir, False);
470         }
471         else
472                 pdb_set_homedir(sampass, homedir, True);
473
474         if (!get_single_attribute(ldap_struct, entry, "scriptPath", logon_script)) {
475                 pstrcpy(logon_script, lp_logon_script());
476                 standard_sub_advanced(-1, username, "", gid, username, logon_script);
477                 DEBUG(5,("scriptPath fell back to %s\n",logon_script));
478                 pdb_set_logon_script(sampass, logon_script, False);
479         }
480         else
481                 pdb_set_logon_script(sampass, logon_script, True);
482
483         if (!get_single_attribute(ldap_struct, entry, "profilePath", profile_path)) {
484                 pstrcpy(profile_path, lp_logon_path());
485                 standard_sub_advanced(-1, username, "", gid, username, profile_path);
486                 DEBUG(5,("profilePath fell back to %s\n",profile_path));
487                 pdb_set_profile_path(sampass, profile_path, False);
488         }
489         else
490                 pdb_set_profile_path(sampass, profile_path, True);
491                 
492         get_single_attribute(ldap_struct, entry, "description", acct_desc);
493         get_single_attribute(ldap_struct, entry, "userWorkstations", workstations);
494         get_single_attribute(ldap_struct, entry, "rid", temp);
495         user_rid = (uint32)strtol(temp, NULL, 10);
496         get_single_attribute(ldap_struct, entry, "primaryGroupID", temp);
497         group_rid = (uint32)strtol(temp, NULL, 10);
498
499
500         /* These values MAY be in LDAP, but they can also be retrieved through 
501          *  sys_getpw*() which is how we're doing it 
502          */
503         pw = getpwnam_alloc(username);
504         if (pw == NULL) {
505                 DEBUG (2,("init_sam_from_ldap: User [%s] does not ave a uid!\n", username));
506                 return False;
507         }
508         uid = pw->pw_uid;
509         gid = pw->pw_gid;
510
511         passwd_free(&pw);
512
513         /* FIXME: hours stuff should be cleaner */
514         
515         logon_divs = 168;
516         hours_len = 21;
517         memset(hours, 0xff, hours_len);
518
519         get_single_attribute (ldap_struct, entry, "lmPassword", temp);
520         pdb_gethexpwd(temp, smblmpwd);
521         memset((char *)temp, '\0', sizeof(temp));
522         get_single_attribute (ldap_struct, entry, "ntPassword", temp);
523         pdb_gethexpwd(temp, smbntpwd);
524         memset((char *)temp, '\0', sizeof(temp));
525         get_single_attribute (ldap_struct, entry, "acctFlags", temp);
526         acct_ctrl = pdb_decode_acct_ctrl(temp);
527
528         if (acct_ctrl == 0)
529                 acct_ctrl |= ACB_NORMAL;
530
531         pdb_set_uid(sampass, uid);
532         pdb_set_gid(sampass, gid);
533         
534         pdb_set_acct_ctrl(sampass, acct_ctrl);
535         pdb_set_logon_time(sampass, logon_time);
536         pdb_set_logoff_time(sampass, logoff_time);
537         pdb_set_kickoff_time(sampass, kickoff_time);
538         pdb_set_pass_can_change_time(sampass, pass_can_change_time);
539         pdb_set_pass_must_change_time(sampass, pass_must_change_time);
540         pdb_set_pass_last_set_time(sampass, pass_last_set_time);
541
542         pdb_set_hours_len(sampass, hours_len);
543         pdb_set_logon_divs(sampass, logon_divs);
544
545         pdb_set_user_rid(sampass, user_rid);
546         pdb_set_group_rid(sampass, group_rid);
547
548         pdb_set_username(sampass, username);
549
550         pdb_set_domain(sampass, domain);
551         pdb_set_nt_username(sampass, nt_username);
552
553         pdb_set_fullname(sampass, fullname);
554
555         pdb_set_acct_desc(sampass, acct_desc);
556         pdb_set_workstations(sampass, workstations);
557         pdb_set_munged_dial(sampass, munged_dial);
558         
559         if (!pdb_set_nt_passwd(sampass, smbntpwd))
560                 return False;
561         if (!pdb_set_lanman_passwd(sampass, smblmpwd))
562                 return False;
563
564         /* pdb_set_unknown_3(sampass, unknown3); */
565         /* pdb_set_unknown_5(sampass, unknown5); */
566         /* pdb_set_unknown_6(sampass, unknown6); */
567
568         pdb_set_hours(sampass, hours);
569
570         return True;
571 }
572
573 /**********************************************************************
574 Initialize SAM_ACCOUNT from an LDAP query
575 (Based on init_buffer_from_sam in pdb_tdb.c)
576 *********************************************************************/
577 static BOOL init_ldap_from_sam (LDAPMod *** mods, int ldap_state, const SAM_ACCOUNT * sampass)
578 {
579         pstring temp;
580
581         if (mods == NULL || sampass == NULL) {
582                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
583                 return False;
584         }
585
586         *mods = NULL;
587
588         /* 
589          * took out adding "objectclass: sambaAccount"
590          * do this on a per-mod basis
591          */
592
593
594         make_a_mod(mods, ldap_state, "uid", pdb_get_username(sampass));
595         DEBUG(2, ("Setting entry for user: %s\n", pdb_get_username(sampass)));
596
597         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
598         make_a_mod(mods, ldap_state, "pwdLastSet", temp);
599
600         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
601         make_a_mod(mods, ldap_state, "logonTime", temp);
602
603         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
604         make_a_mod(mods, ldap_state, "logoffTime", temp);
605
606         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
607         make_a_mod(mods, ldap_state, "kickoffTime", temp);
608
609         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
610         make_a_mod(mods, ldap_state, "pwdCanChange", temp);
611
612         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
613         make_a_mod(mods, ldap_state, "pwdMustChange", temp);
614
615         /* displayName, cn, and gecos should all be the same
616            *  most easily accomplished by giving them the same OID
617            *  gecos isn't set here b/c it should be handled by the 
618            *  add-user script
619          */
620
621         make_a_mod(mods, ldap_state, "displayName", pdb_get_fullname(sampass));
622         make_a_mod(mods, ldap_state, "cn", pdb_get_fullname(sampass));
623         make_a_mod(mods, ldap_state, "description", pdb_get_acct_desc(sampass));
624         make_a_mod(mods, ldap_state, "userWorkstations", pdb_get_workstations(sampass));
625
626         /*
627          * Only updates fields which have been set (not defaults from smb.conf)
628          */
629
630         if (IS_SAM_SET(sampass, FLAG_SAM_SMBHOME))
631         make_a_mod(mods, ldap_state, "smbHome", pdb_get_homedir(sampass));
632                 
633         if (IS_SAM_SET(sampass, FLAG_SAM_DRIVE))
634         make_a_mod(mods, ldap_state, "homeDrive", pdb_get_dirdrive(sampass));
635                 
636         if (IS_SAM_SET(sampass, FLAG_SAM_LOGONSCRIPT))
637         make_a_mod(mods, ldap_state, "scriptPath", pdb_get_logon_script(sampass));
638
639         if (IS_SAM_SET(sampass, FLAG_SAM_PROFILE))
640         make_a_mod(mods, ldap_state, "profilePath", pdb_get_profile_path(sampass));
641
642
643         if ( !pdb_get_user_rid(sampass))
644                 slprintf(temp, sizeof(temp) - 1, "%i", pdb_uid_to_user_rid(pdb_get_uid(sampass)));
645         else
646                 slprintf(temp, sizeof(temp) - 1, "%i", pdb_get_user_rid(sampass));
647         make_a_mod(mods, ldap_state, "rid", temp);
648
649         if ( !pdb_get_group_rid(sampass))
650                 slprintf(temp, sizeof(temp) - 1, "%i", pdb_gid_to_group_rid(pdb_get_gid(sampass)));
651         else
652                 slprintf(temp, sizeof(temp) - 1, "%i", pdb_get_group_rid(sampass));
653         make_a_mod(mods, ldap_state, "primaryGroupID", temp);
654
655         /* FIXME: Hours stuff goes in LDAP  */
656         pdb_sethexpwd (temp, pdb_get_lanman_passwd(sampass), pdb_get_acct_ctrl(sampass));
657         make_a_mod (mods, ldap_state, "lmPassword", temp);
658         
659         pdb_sethexpwd (temp, pdb_get_nt_passwd(sampass), pdb_get_acct_ctrl(sampass));
660         make_a_mod (mods, ldap_state, "ntPassword", temp);
661         
662         make_a_mod (mods, ldap_state, "acctFlags", pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass),
663                 NEW_PW_FORMAT_SPACE_PADDED_LEN));
664
665         return True;
666 }
667
668 /**********************************************************************
669 Connect to LDAP server for password enumeration
670 *********************************************************************/
671 BOOL pdb_setsampwent(BOOL update)
672 {
673         int rc;
674         pstring filter;
675
676         if (!ldap_open_connection(&global_ldap_ent.ldap_struct))
677         {
678                 return False;
679         }
680         if (!ldap_connect_system(global_ldap_ent.ldap_struct))
681         {
682                 ldap_unbind(global_ldap_ent.ldap_struct);
683                 return False;
684         }
685
686         pstrcpy(filter, lp_ldap_filter());
687         all_string_sub(filter, "%u", "*", sizeof(pstring));
688
689         rc = ldap_search_s(global_ldap_ent.ldap_struct, lp_ldap_suffix(),
690                            LDAP_SCOPE_SUBTREE, filter, NULL, 0,
691                            &global_ldap_ent.result);
692
693         if (rc != LDAP_SUCCESS)
694         {
695                 DEBUG(0, ("LDAP search failed: %s\n", ldap_err2string(rc)));
696                 DEBUG(3, ("Query was: %s, %s\n", lp_ldap_suffix(), filter));
697                 ldap_msgfree(global_ldap_ent.result);
698                 ldap_unbind(global_ldap_ent.ldap_struct);
699                 global_ldap_ent.ldap_struct = NULL;
700                 global_ldap_ent.result = NULL;
701                 return False;
702         }
703
704         DEBUG(2, ("pdb_setsampwent: %d entries in the base!\n",
705                 ldap_count_entries(global_ldap_ent.ldap_struct,
706                 global_ldap_ent.result)));
707
708         global_ldap_ent.entry = ldap_first_entry(global_ldap_ent.ldap_struct,
709                                  global_ldap_ent.result);
710
711         return True;
712 }
713
714 /**********************************************************************
715 End enumeration of the LDAP password list 
716 *********************************************************************/
717 void pdb_endsampwent(void)
718 {
719         if (global_ldap_ent.ldap_struct && global_ldap_ent.result)
720         {
721                 ldap_msgfree(global_ldap_ent.result);
722                 ldap_unbind(global_ldap_ent.ldap_struct);
723                 global_ldap_ent.ldap_struct = NULL;
724                 global_ldap_ent.result = NULL;
725         }
726 }
727
728 /**********************************************************************
729 Get the next entry in the LDAP password database 
730 *********************************************************************/
731 BOOL pdb_getsampwent(SAM_ACCOUNT * user)
732 {
733         if (!global_ldap_ent.entry)
734                 return False;
735
736         global_ldap_ent.entry = ldap_next_entry(global_ldap_ent.ldap_struct,
737                                 global_ldap_ent.entry);
738
739         if (global_ldap_ent.entry != NULL)
740         {
741                 return init_sam_from_ldap(user, global_ldap_ent.ldap_struct,
742                                           global_ldap_ent.entry);
743         }
744         return False;
745 }
746
747 /**********************************************************************
748 Get SAM_ACCOUNT entry from LDAP by username 
749 *********************************************************************/
750 BOOL pdb_getsampwnam(SAM_ACCOUNT * user, const char *sname)
751 {
752         LDAP *ldap_struct;
753         LDAPMessage *result;
754         LDAPMessage *entry;
755
756         if (!ldap_open_connection(&ldap_struct))
757                 return False;
758         if (!ldap_connect_system(ldap_struct))
759         {
760                 ldap_unbind(ldap_struct);
761                 return False;
762         }
763         if (ldap_search_one_user_by_name(ldap_struct, sname, &result) != LDAP_SUCCESS)
764         {
765                 ldap_unbind(ldap_struct);
766                 return False;
767         }
768         if (ldap_count_entries(ldap_struct, result) < 1)
769         {
770                 DEBUG(0,
771                       ("We don't find this user [%s] count=%d\n", sname,
772                        ldap_count_entries(ldap_struct, result)));
773                 ldap_unbind(ldap_struct);
774                 return False;
775         }
776         entry = ldap_first_entry(ldap_struct, result);
777         if (entry)
778         {
779                 init_sam_from_ldap(user, ldap_struct, entry);
780                 ldap_msgfree(result);
781                 ldap_unbind(ldap_struct);
782                 return True;
783         }
784         else
785         {
786                 ldap_msgfree(result);
787                 ldap_unbind(ldap_struct);
788                 return False;
789         }
790 }
791
792 /**********************************************************************
793 Get SAM_ACCOUNT entry from LDAP by rid 
794 *********************************************************************/
795 BOOL pdb_getsampwrid(SAM_ACCOUNT * user, uint32 rid)
796 {
797         LDAP *ldap_struct;
798         LDAPMessage *result;
799         LDAPMessage *entry;
800
801         if (!ldap_open_connection(&ldap_struct))
802                 return False;
803
804         if (!ldap_connect_system(ldap_struct))
805         {
806                 ldap_unbind(ldap_struct);
807                 return False;
808         }
809         if (ldap_search_one_user_by_rid(ldap_struct, rid, &result) !=
810             LDAP_SUCCESS)
811         {
812                 ldap_unbind(ldap_struct);
813                 return False;
814         }
815
816         if (ldap_count_entries(ldap_struct, result) < 1)
817         {
818                 DEBUG(0,
819                       ("We don't find this rid [%i] count=%d\n", rid,
820                        ldap_count_entries(ldap_struct, result)));
821                 ldap_unbind(ldap_struct);
822                 return False;
823         }
824
825         entry = ldap_first_entry(ldap_struct, result);
826         if (entry)
827         {
828                 init_sam_from_ldap(user, ldap_struct, entry);
829                 ldap_msgfree(result);
830                 ldap_unbind(ldap_struct);
831                 return True;
832         }
833         else
834         {
835                 ldap_msgfree(result);
836                 ldap_unbind(ldap_struct);
837                 return False;
838         }
839 }
840
841 /**********************************************************************
842 Delete entry from LDAP for username 
843 *********************************************************************/
844 BOOL pdb_delete_sam_account(SAM_ACCOUNT * sam_acct)
845 {
846         const char *sname;
847         int rc;
848         char *dn;
849         LDAP *ldap_struct;
850         LDAPMessage *entry;
851         LDAPMessage *result;
852
853         if (!sam_acct) {
854                 DEBUG(0, ("sam_acct was NULL!\n"));
855                 return False;
856         }
857
858         sname = pdb_get_username(sam_acct);
859
860         if (!ldap_open_connection (&ldap_struct))
861                 return False;
862
863         DEBUG (3, ("Deleting user %s from LDAP.\n", sname));
864         
865         if (!ldap_connect_system (ldap_struct)) {
866                 ldap_unbind (ldap_struct);
867                 DEBUG(0, ("Failed to delete user %s from LDAP.\n", sname));
868                 return False;
869         }
870
871         rc = ldap_search_one_user_by_name (ldap_struct, sname, &result);
872         if (ldap_count_entries (ldap_struct, result) == 0) {
873                 DEBUG (0, ("User doesn't exit!\n"));
874                 ldap_msgfree (result);
875                 ldap_unbind (ldap_struct);
876                 return False;
877         }
878
879         entry = ldap_first_entry (ldap_struct, result);
880         dn = ldap_get_dn (ldap_struct, entry);
881
882         rc = ldap_delete_s (ldap_struct, dn);
883
884         ldap_memfree (dn);
885         if (rc != LDAP_SUCCESS) {
886                 char *ld_error;
887                 ldap_get_option (ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
888                 DEBUG (0,("failed to delete user with uid = %s with: %s\n\t%s\n",
889                         sname, ldap_err2string (rc), ld_error));
890                 free (ld_error);
891                 ldap_unbind (ldap_struct);
892                 return False;
893         }
894
895         DEBUG (2,("successfully deleted uid = %s from the LDAP database\n", sname));
896         ldap_unbind (ldap_struct);
897         return True;
898 }
899
900 /**********************************************************************
901 Update SAM_ACCOUNT 
902 *********************************************************************/
903 BOOL pdb_update_sam_account(SAM_ACCOUNT * newpwd)
904 {
905         int rc;
906         char *dn;
907         LDAP *ldap_struct;
908         LDAPMessage *result;
909         LDAPMessage *entry;
910         LDAPMod **mods;
911
912         if (!ldap_open_connection(&ldap_struct)) /* open a connection to the server */
913                 return False;
914
915         if (!ldap_connect_system(ldap_struct))  /* connect as system account */
916         {
917                 ldap_unbind(ldap_struct);
918                 return False;
919         }
920
921         rc = ldap_search_one_user_by_name(ldap_struct,
922                                           pdb_get_username(newpwd), &result);
923
924         if (ldap_count_entries(ldap_struct, result) == 0)
925         {
926                 DEBUG(0, ("No user to modify!\n"));
927                 ldap_msgfree(result);
928                 ldap_unbind(ldap_struct);
929                 return False;
930         }
931
932         init_ldap_from_sam(&mods, LDAP_MOD_REPLACE, newpwd);
933
934         entry = ldap_first_entry(ldap_struct, result);
935         dn = ldap_get_dn(ldap_struct, entry);
936
937         rc = ldap_modify_s(ldap_struct, dn, mods);
938
939         if (rc != LDAP_SUCCESS)
940         {
941                 char *ld_error;
942                 ldap_get_option(ldap_struct, LDAP_OPT_ERROR_STRING,
943                                 &ld_error);
944                 DEBUG(0,
945                       ("failed to modify user with uid = %s with: %s\n\t%s\n",
946                        pdb_get_username(newpwd), ldap_err2string(rc),
947                        ld_error));
948                 free(ld_error);
949                 ldap_unbind(ldap_struct);
950                 return False;
951         }
952
953         DEBUG(2,
954               ("successfully modified uid = %s in the LDAP database\n",
955                pdb_get_username(newpwd)));
956         ldap_mods_free(mods, 1);
957         ldap_unbind(ldap_struct);
958         return True;
959 }
960
961 /**********************************************************************
962 Add SAM_ACCOUNT to LDAP 
963 *********************************************************************/
964 BOOL pdb_add_sam_account(SAM_ACCOUNT * newpwd)
965 {
966         int rc;
967         pstring filter;
968         LDAP *ldap_struct;
969         LDAPMessage *result;
970         pstring dn;
971         LDAPMod **mods;
972         int             ldap_op;
973         uint32          num_result;
974
975         if (!ldap_open_connection(&ldap_struct))        /* open a connection to the server */
976         {
977                 return False;
978         }
979
980         if (!ldap_connect_system(ldap_struct))  /* connect as system account */
981         {
982                 ldap_unbind(ldap_struct);
983                 return False;
984         }
985
986         rc = ldap_search_one_user_by_name (ldap_struct, pdb_get_username(newpwd), &result);
987
988         if (ldap_count_entries(ldap_struct, result) != 0)
989         {
990                 DEBUG(0,("User already in the base, with samba properties\n"));
991                 ldap_msgfree(result);
992                 ldap_unbind(ldap_struct);
993                 return False;
994         }
995         ldap_msgfree(result);
996
997         slprintf (filter, sizeof (filter) - 1, "uid=%s", pdb_get_username(newpwd));
998         rc = ldap_search_one_user(ldap_struct, filter, &result);
999         num_result = ldap_count_entries(ldap_struct, result);
1000         
1001         if (num_result > 1) {
1002                 DEBUG (0, ("More than one user with that uid exists: bailing out!\n"));
1003                 return False;
1004         }
1005         
1006         /* Check if we need to update an existing entry */
1007         if (num_result == 1) {
1008                 char *tmp;
1009                 LDAPMessage *entry;
1010                 
1011                 DEBUG(3,("User exists without samba properties: adding them\n"));
1012                 ldap_op = LDAP_MOD_REPLACE;
1013                 entry = ldap_first_entry (ldap_struct, result);
1014                 tmp = ldap_get_dn (ldap_struct, entry);
1015                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1016                 ldap_memfree (tmp);
1017         }
1018         else {
1019                 /* Check if we need to add an entry */
1020                 DEBUG(3,("Adding new user\n"));
1021                 ldap_op = LDAP_MOD_ADD;
1022                 slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", pdb_get_username(newpwd), lp_ldap_suffix ());
1023         }
1024
1025         ldap_msgfree(result);
1026
1027         init_ldap_from_sam(&mods, ldap_op, newpwd);
1028         make_a_mod(&mods, LDAP_MOD_ADD, "objectclass", "sambaAccount");
1029
1030         if (ldap_op == LDAP_MOD_REPLACE) {
1031                 rc = ldap_modify_s(ldap_struct, dn, mods);
1032         }
1033         else {
1034                 rc = ldap_add_s(ldap_struct, dn, mods);
1035         }
1036
1037         if (rc != LDAP_SUCCESS)
1038         {
1039                 char *ld_error;
1040
1041                 ldap_get_option (ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
1042                 DEBUG(0,("failed to modify user with uid = %s with: %s\n\t%s\n",
1043                         pdb_get_username(newpwd), ldap_err2string (rc), ld_error));
1044                 free(ld_error);
1045                 ldap_mods_free(mods, 1);
1046                 ldap_unbind(ldap_struct);
1047                 return False;
1048         }
1049         
1050         DEBUG(2,("added: uid = %s in the LDAP database\n", pdb_get_username(newpwd)));
1051         ldap_mods_free(mods, 1);
1052         ldap_unbind(ldap_struct);
1053         return True;
1054 }
1055
1056 #else
1057 void dummy_function(void);
1058 void
1059 dummy_function (void)
1060 {
1061 }                               /* stop some compilers complaining */
1062 #endif