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