r7372: abartet's patch for BUG 2391 (segv caused by free a static pointer)
[Samba/gbeck.git] / source / lib / smbldap.c
blob4a8ef63806f58e132a135732c0d8d419796ec36a
1 /*
2 Unix SMB/CIFS implementation.
3 LDAP protocol helper functions for SAMBA
4 Copyright (C) Jean François Micouleau 1998
5 Copyright (C) Gerald Carter 2001-2003
6 Copyright (C) Shahms King 2001
7 Copyright (C) Andrew Bartlett 2002-2003
8 Copyright (C) Stefan (metze) Metzmacher 2002-2003
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 #include "includes.h"
27 #include "smbldap.h"
29 #ifndef LDAP_OPT_SUCCESS
30 #define LDAP_OPT_SUCCESS 0
31 #endif
33 /* Try not to hit the up or down server forever */
35 #define SMBLDAP_DONT_PING_TIME 10 /* ping only all 10 seconds */
36 #define SMBLDAP_NUM_RETRIES 8 /* retry only 8 times */
38 #define SMBLDAP_IDLE_TIME 150 /* After 2.5 minutes disconnect */
41 /* attributes used by Samba 2.2 */
43 ATTRIB_MAP_ENTRY attrib_map_v22[] = {
44 { LDAP_ATTR_UID, "uid" },
45 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
46 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
47 { LDAP_ATTR_UNIX_HOME, "homeDirectory" },
48 { LDAP_ATTR_PWD_LAST_SET, "pwdLastSet" },
49 { LDAP_ATTR_PWD_CAN_CHANGE, "pwdCanChange" },
50 { LDAP_ATTR_PWD_MUST_CHANGE, "pwdMustChange" },
51 { LDAP_ATTR_LOGON_TIME, "logonTime" },
52 { LDAP_ATTR_LOGOFF_TIME, "logoffTime" },
53 { LDAP_ATTR_KICKOFF_TIME, "kickoffTime" },
54 { LDAP_ATTR_CN, "cn" },
55 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
56 { LDAP_ATTR_HOME_PATH, "smbHome" },
57 { LDAP_ATTR_HOME_DRIVE, "homeDrive" },
58 { LDAP_ATTR_LOGON_SCRIPT, "scriptPath" },
59 { LDAP_ATTR_PROFILE_PATH, "profilePath" },
60 { LDAP_ATTR_DESC, "description" },
61 { LDAP_ATTR_USER_WKS, "userWorkstations"},
62 { LDAP_ATTR_USER_RID, "rid" },
63 { LDAP_ATTR_PRIMARY_GROUP_RID, "primaryGroupID"},
64 { LDAP_ATTR_LMPW, "lmPassword" },
65 { LDAP_ATTR_NTPW, "ntPassword" },
66 { LDAP_ATTR_DOMAIN, "domain" },
67 { LDAP_ATTR_OBJCLASS, "objectClass" },
68 { LDAP_ATTR_ACB_INFO, "acctFlags" },
69 { LDAP_ATTR_MOD_TIMESTAMP, "modifyTimestamp" },
70 { LDAP_ATTR_LIST_END, NULL }
73 ATTRIB_MAP_ENTRY attrib_map_to_delete_v22[] = {
74 { LDAP_ATTR_PWD_LAST_SET, "pwdLastSet" },
75 { LDAP_ATTR_PWD_CAN_CHANGE, "pwdCanChange" },
76 { LDAP_ATTR_PWD_MUST_CHANGE, "pwdMustChange" },
77 { LDAP_ATTR_LOGON_TIME, "logonTime" },
78 { LDAP_ATTR_LOGOFF_TIME, "logoffTime" },
79 { LDAP_ATTR_KICKOFF_TIME, "kickoffTime" },
80 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
81 { LDAP_ATTR_HOME_PATH, "smbHome" },
82 { LDAP_ATTR_HOME_DRIVE, "homeDrives" },
83 { LDAP_ATTR_LOGON_SCRIPT, "scriptPath" },
84 { LDAP_ATTR_PROFILE_PATH, "profilePath" },
85 { LDAP_ATTR_USER_WKS, "userWorkstations"},
86 { LDAP_ATTR_USER_RID, "rid" },
87 { LDAP_ATTR_PRIMARY_GROUP_RID, "primaryGroupID"},
88 { LDAP_ATTR_LMPW, "lmPassword" },
89 { LDAP_ATTR_NTPW, "ntPassword" },
90 { LDAP_ATTR_DOMAIN, "domain" },
91 { LDAP_ATTR_ACB_INFO, "acctFlags" },
92 { LDAP_ATTR_LIST_END, NULL }
95 /* attributes used by Samba 3.0's sambaSamAccount */
97 ATTRIB_MAP_ENTRY attrib_map_v30[] = {
98 { LDAP_ATTR_UID, "uid" },
99 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
100 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
101 { LDAP_ATTR_UNIX_HOME, "homeDirectory" },
102 { LDAP_ATTR_PWD_LAST_SET, "sambaPwdLastSet" },
103 { LDAP_ATTR_PWD_CAN_CHANGE, "sambaPwdCanChange" },
104 { LDAP_ATTR_PWD_MUST_CHANGE, "sambaPwdMustChange" },
105 { LDAP_ATTR_LOGON_TIME, "sambaLogonTime" },
106 { LDAP_ATTR_LOGOFF_TIME, "sambaLogoffTime" },
107 { LDAP_ATTR_KICKOFF_TIME, "sambaKickoffTime" },
108 { LDAP_ATTR_CN, "cn" },
109 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
110 { LDAP_ATTR_HOME_DRIVE, "sambaHomeDrive" },
111 { LDAP_ATTR_HOME_PATH, "sambaHomePath" },
112 { LDAP_ATTR_LOGON_SCRIPT, "sambaLogonScript" },
113 { LDAP_ATTR_PROFILE_PATH, "sambaProfilePath" },
114 { LDAP_ATTR_DESC, "description" },
115 { LDAP_ATTR_USER_WKS, "sambaUserWorkstations" },
116 { LDAP_ATTR_USER_SID, LDAP_ATTRIBUTE_SID },
117 { LDAP_ATTR_PRIMARY_GROUP_SID, "sambaPrimaryGroupSID" },
118 { LDAP_ATTR_LMPW, "sambaLMPassword" },
119 { LDAP_ATTR_NTPW, "sambaNTPassword" },
120 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
121 { LDAP_ATTR_OBJCLASS, "objectClass" },
122 { LDAP_ATTR_ACB_INFO, "sambaAcctFlags" },
123 { LDAP_ATTR_MUNGED_DIAL, "sambaMungedDial" },
124 { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
125 { LDAP_ATTR_BAD_PASSWORD_TIME, "sambaBadPasswordTime" },
126 { LDAP_ATTR_PWD_HISTORY, "sambaPasswordHistory" },
127 { LDAP_ATTR_MOD_TIMESTAMP, "modifyTimestamp" },
128 { LDAP_ATTR_LOGON_HOURS, "sambaLogonHours" },
129 { LDAP_ATTR_LIST_END, NULL }
132 ATTRIB_MAP_ENTRY attrib_map_to_delete_v30[] = {
133 { LDAP_ATTR_PWD_LAST_SET, "sambaPwdLastSet" },
134 { LDAP_ATTR_PWD_CAN_CHANGE, "sambaPwdCanChange" },
135 { LDAP_ATTR_PWD_MUST_CHANGE, "sambaPwdMustChange" },
136 { LDAP_ATTR_LOGON_TIME, "sambaLogonTime" },
137 { LDAP_ATTR_LOGOFF_TIME, "sambaLogoffTime" },
138 { LDAP_ATTR_KICKOFF_TIME, "sambaKickoffTime" },
139 { LDAP_ATTR_HOME_DRIVE, "sambaHomeDrive" },
140 { LDAP_ATTR_HOME_PATH, "sambaHomePath" },
141 { LDAP_ATTR_LOGON_SCRIPT, "sambaLogonScript" },
142 { LDAP_ATTR_PROFILE_PATH, "sambaProfilePath" },
143 { LDAP_ATTR_USER_WKS, "sambaUserWorkstations" },
144 { LDAP_ATTR_USER_SID, LDAP_ATTRIBUTE_SID },
145 { LDAP_ATTR_PRIMARY_GROUP_SID, "sambaPrimaryGroupSID" },
146 { LDAP_ATTR_LMPW, "sambaLMPassword" },
147 { LDAP_ATTR_NTPW, "sambaNTPassword" },
148 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
149 { LDAP_ATTR_ACB_INFO, "sambaAcctFlags" },
150 { LDAP_ATTR_MUNGED_DIAL, "sambaMungedDial" },
151 { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
152 { LDAP_ATTR_BAD_PASSWORD_TIME, "sambaBadPasswordTime" },
153 { LDAP_ATTR_PWD_HISTORY, "sambaPasswordHistory" },
154 { LDAP_ATTR_LOGON_HOURS, "sambaLogonHours" },
155 { LDAP_ATTR_LIST_END, NULL }
158 /* attributes used for allocating RIDs */
160 ATTRIB_MAP_ENTRY dominfo_attr_list[] = {
161 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
162 { LDAP_ATTR_NEXT_RID, "sambaNextRid" },
163 { LDAP_ATTR_NEXT_USERRID, "sambaNextUserRid" },
164 { LDAP_ATTR_NEXT_GROUPRID, "sambaNextGroupRid" },
165 { LDAP_ATTR_DOM_SID, LDAP_ATTRIBUTE_SID },
166 { LDAP_ATTR_ALGORITHMIC_RID_BASE,"sambaAlgorithmicRidBase"},
167 { LDAP_ATTR_OBJCLASS, "objectClass" },
168 { LDAP_ATTR_LIST_END, NULL },
171 /* Samba 3.0 group mapping attributes */
173 ATTRIB_MAP_ENTRY groupmap_attr_list[] = {
174 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
175 { LDAP_ATTR_GROUP_SID, LDAP_ATTRIBUTE_SID },
176 { LDAP_ATTR_GROUP_TYPE, "sambaGroupType" },
177 { LDAP_ATTR_SID_LIST, "sambaSIDList" },
178 { LDAP_ATTR_DESC, "description" },
179 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
180 { LDAP_ATTR_CN, "cn" },
181 { LDAP_ATTR_OBJCLASS, "objectClass" },
182 { LDAP_ATTR_LIST_END, NULL }
185 ATTRIB_MAP_ENTRY groupmap_attr_list_to_delete[] = {
186 { LDAP_ATTR_GROUP_SID, LDAP_ATTRIBUTE_SID },
187 { LDAP_ATTR_GROUP_TYPE, "sambaGroupType" },
188 { LDAP_ATTR_DESC, "description" },
189 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
190 { LDAP_ATTR_SID_LIST, "sambaSIDList" },
191 { LDAP_ATTR_LIST_END, NULL }
194 /* idmap_ldap sambaUnixIdPool */
196 ATTRIB_MAP_ENTRY idpool_attr_list[] = {
197 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
198 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
199 { LDAP_ATTR_OBJCLASS, "objectClass" },
200 { LDAP_ATTR_LIST_END, NULL }
203 ATTRIB_MAP_ENTRY sidmap_attr_list[] = {
204 { LDAP_ATTR_SID, LDAP_ATTRIBUTE_SID },
205 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
206 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
207 { LDAP_ATTR_OBJCLASS, "objectClass" },
208 { LDAP_ATTR_LIST_END, NULL }
211 /**********************************************************************
212 perform a simple table lookup and return the attribute name
213 **********************************************************************/
215 const char* get_attr_key2string( ATTRIB_MAP_ENTRY table[], int key )
217 int i = 0;
219 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
220 if ( table[i].attrib == key )
221 return table[i].name;
222 i++;
225 return NULL;
229 /**********************************************************************
230 Return the list of attribute names from a mapping table
231 **********************************************************************/
233 const char** get_attr_list( ATTRIB_MAP_ENTRY table[] )
235 const char **names;
236 int i = 0;
238 while ( table[i].attrib != LDAP_ATTR_LIST_END )
239 i++;
240 i++;
242 names = SMB_MALLOC_ARRAY( const char*, i );
243 if ( !names ) {
244 DEBUG(0,("get_attr_list: out of memory\n"));
245 return NULL;
248 i = 0;
249 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
250 names[i] = SMB_STRDUP( table[i].name );
251 i++;
253 names[i] = NULL;
255 return names;
258 /*********************************************************************
259 Cleanup
260 ********************************************************************/
262 void free_attr_list( const char **list )
264 int i = 0;
266 if ( !list )
267 return;
269 while ( list[i] ) {
270 SAFE_FREE( list[i] );
271 i+=1;
274 SAFE_FREE( list );
277 /*******************************************************************
278 Search an attribute and return the first value found.
279 ******************************************************************/
281 BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
282 const char *attribute, char *value,
283 int max_len)
285 char **values;
287 if ( !attribute )
288 return False;
290 value[0] = '\0';
292 if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
293 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
295 return False;
298 if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, max_len, False) == (size_t)-1) {
299 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n",
300 attribute, values[0]));
301 ldap_value_free(values);
302 return False;
305 ldap_value_free(values);
306 #ifdef DEBUG_PASSWORDS
307 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
308 #endif
309 return True;
312 BOOL smbldap_get_single_pstring (LDAP * ldap_struct, LDAPMessage * entry,
313 const char *attribute, pstring value)
315 return smbldap_get_single_attribute(ldap_struct, entry,
316 attribute, value,
317 sizeof(pstring));
320 /************************************************************************
321 Routine to manage the LDAPMod structure array
322 manage memory used by the array, by each struct, and values
323 ***********************************************************************/
325 void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
327 LDAPMod **mods;
328 int i;
329 int j;
331 mods = *modlist;
333 /* sanity checks on the mod values */
335 if (attribute == NULL || *attribute == '\0') {
336 return;
339 #if 0 /* commented out after discussion with abartlet. Do not reenable.
340 left here so other do not re-add similar code --jerry */
341 if (value == NULL || *value == '\0')
342 return;
343 #endif
345 if (mods == NULL) {
346 mods = SMB_MALLOC_P(LDAPMod *);
347 if (mods == NULL) {
348 DEBUG(0, ("make_a_mod: out of memory!\n"));
349 return;
351 mods[0] = NULL;
354 for (i = 0; mods[i] != NULL; ++i) {
355 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
356 break;
359 if (mods[i] == NULL) {
360 mods = SMB_REALLOC_ARRAY (mods, LDAPMod *, i + 2);
361 if (mods == NULL) {
362 DEBUG(0, ("make_a_mod: out of memory!\n"));
363 return;
365 mods[i] = SMB_MALLOC_P(LDAPMod);
366 if (mods[i] == NULL) {
367 DEBUG(0, ("make_a_mod: out of memory!\n"));
368 return;
370 mods[i]->mod_op = modop;
371 mods[i]->mod_values = NULL;
372 mods[i]->mod_type = SMB_STRDUP(attribute);
373 mods[i + 1] = NULL;
376 if (value != NULL) {
377 char *utf8_value = NULL;
379 j = 0;
380 if (mods[i]->mod_values != NULL) {
381 for (; mods[i]->mod_values[j] != NULL; j++);
383 mods[i]->mod_values = SMB_REALLOC_ARRAY(mods[i]->mod_values, char *, j + 2);
385 if (mods[i]->mod_values == NULL) {
386 DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
387 return;
390 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
391 DEBUG (0, ("make_a_mod: String conversion failure!\n"));
392 return;
395 mods[i]->mod_values[j] = utf8_value;
397 mods[i]->mod_values[j + 1] = NULL;
399 *modlist = mods;
402 /**********************************************************************
403 Set attribute to newval in LDAP, regardless of what value the
404 attribute had in LDAP before.
405 *********************************************************************/
407 void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
408 LDAPMod ***mods,
409 const char *attribute, const char *newval)
411 char oldval[2048]; /* current largest allowed value is mungeddial */
412 BOOL existed;
414 if (attribute == NULL) {
415 /* This can actually happen for ldapsam_compat where we for
416 * example don't have a password history */
417 return;
420 if (existing != NULL) {
421 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval, sizeof(oldval));
422 } else {
423 existed = False;
424 *oldval = '\0';
427 /* all of our string attributes are case insensitive */
429 if (existed && newval && (StrCaseCmp(oldval, newval) == 0)) {
431 /* Believe it or not, but LDAP will deny a delete and
432 an add at the same time if the values are the
433 same... */
434 return;
437 if (existed) {
438 /* There has been no value before, so don't delete it.
439 * Here's a possible race: We might end up with
440 * duplicate attributes */
441 /* By deleting exactly the value we found in the entry this
442 * should be race-free in the sense that the LDAP-Server will
443 * deny the complete operation if somebody changed the
444 * attribute behind our back. */
445 /* This will also allow modifying single valued attributes
446 * in Novell NDS. In NDS you have to first remove attribute and then
447 * you could add new value */
449 smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, oldval);
452 /* Regardless of the real operation (add or modify)
453 we add the new value here. We rely on deleting
454 the old value, should it exist. */
456 if ((newval != NULL) && (strlen(newval) > 0)) {
457 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
461 /**********************************************************************
462 Some varients of the LDAP rebind code do not pass in the third 'arg'
463 pointer to a void*, so we try and work around it by assuming that the
464 value of the 'LDAP *' pointer is the same as the one we had passed in
465 **********************************************************************/
467 struct smbldap_state_lookup {
468 LDAP *ld;
469 struct smbldap_state *smbldap_state;
470 struct smbldap_state_lookup *prev, *next;
473 static struct smbldap_state_lookup *smbldap_state_lookup_list;
475 static struct smbldap_state *smbldap_find_state(LDAP *ld)
477 struct smbldap_state_lookup *t;
479 for (t = smbldap_state_lookup_list; t; t = t->next) {
480 if (t->ld == ld) {
481 return t->smbldap_state;
484 return NULL;
487 static void smbldap_delete_state(struct smbldap_state *smbldap_state)
489 struct smbldap_state_lookup *t;
491 for (t = smbldap_state_lookup_list; t; t = t->next) {
492 if (t->smbldap_state == smbldap_state) {
493 DLIST_REMOVE(smbldap_state_lookup_list, t);
494 SAFE_FREE(t);
495 return;
500 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state)
502 struct smbldap_state *tmp_ldap_state;
503 struct smbldap_state_lookup *t;
504 struct smbldap_state_lookup *tmp;
506 if ((tmp_ldap_state = smbldap_find_state(ld))) {
507 SMB_ASSERT(tmp_ldap_state == smbldap_state);
508 return;
511 t = SMB_XMALLOC_P(struct smbldap_state_lookup);
512 ZERO_STRUCTP(t);
514 DLIST_ADD_END(smbldap_state_lookup_list, t, tmp);
515 t->ld = ld;
516 t->smbldap_state = smbldap_state;
519 /*******************************************************************
520 open a connection to the ldap server.
521 ******************************************************************/
522 static int smbldap_open_connection (struct smbldap_state *ldap_state)
525 int rc = LDAP_SUCCESS;
526 int version;
527 BOOL ldap_v3 = False;
528 LDAP **ldap_struct = &ldap_state->ldap_struct;
530 #ifdef HAVE_LDAP_INITIALIZE
531 DEBUG(10, ("smbldap_open_connection: %s\n", ldap_state->uri));
533 if ((rc = ldap_initialize(ldap_struct, ldap_state->uri)) != LDAP_SUCCESS) {
534 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
535 return rc;
537 #else
539 /* Parse the string manually */
542 int port = 0;
543 fstring protocol;
544 fstring host;
545 const char *p = ldap_state->uri;
546 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
548 /* skip leading "URL:" (if any) */
549 if ( strnequal( p, "URL:", 4 ) ) {
550 p += 4;
553 sscanf(p, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
555 if (port == 0) {
556 if (strequal(protocol, "ldap")) {
557 port = LDAP_PORT;
558 } else if (strequal(protocol, "ldaps")) {
559 port = LDAPS_PORT;
560 } else {
561 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
565 if ((*ldap_struct = ldap_init(host, port)) == NULL) {
566 DEBUG(0, ("ldap_init failed !\n"));
567 return LDAP_OPERATIONS_ERROR;
570 if (strequal(protocol, "ldaps")) {
571 #ifdef LDAP_OPT_X_TLS
572 int tls = LDAP_OPT_X_TLS_HARD;
573 if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
575 DEBUG(0, ("Failed to setup a TLS session\n"));
578 DEBUG(3,("LDAPS option set...!\n"));
579 #else
580 DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
581 return LDAP_OPERATIONS_ERROR;
582 #endif
585 #endif
587 /* Store the LDAP pointer in a lookup list */
589 smbldap_store_state(*ldap_struct, ldap_state);
591 /* Upgrade to LDAPv3 if possible */
593 if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
595 if (version != LDAP_VERSION3)
597 version = LDAP_VERSION3;
598 if (ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS) {
599 ldap_v3 = True;
601 } else {
602 ldap_v3 = True;
606 if (lp_ldap_ssl() == LDAP_SSL_START_TLS) {
607 #ifdef LDAP_OPT_X_TLS
608 if (ldap_v3) {
609 if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
611 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
612 ldap_err2string(rc)));
613 return rc;
615 DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
616 } else {
618 DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
619 return LDAP_OPERATIONS_ERROR;
621 #else
622 DEBUG(0,("smbldap_open_connection: StartTLS not supported by LDAP client libraries!\n"));
623 return LDAP_OPERATIONS_ERROR;
624 #endif
627 DEBUG(2, ("smbldap_open_connection: connection opened\n"));
628 return rc;
632 /*******************************************************************
633 a rebind function for authenticated referrals
634 This version takes a void* that we can shove useful stuff in :-)
635 ******************************************************************/
636 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
637 #else
638 static int rebindproc_with_state (LDAP * ld, char **whop, char **credp,
639 int *methodp, int freeit, void *arg)
641 struct smbldap_state *ldap_state = arg;
643 /** @TODO Should we be doing something to check what servers we rebind to?
644 Could we get a referral to a machine that we don't want to give our
645 username and password to? */
647 if (freeit) {
648 SAFE_FREE(*whop);
649 memset(*credp, '\0', strlen(*credp));
650 SAFE_FREE(*credp);
651 } else {
652 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n",
653 ldap_state->bind_dn));
655 *whop = SMB_STRDUP(ldap_state->bind_dn);
656 if (!*whop) {
657 return LDAP_NO_MEMORY;
659 *credp = SMB_STRDUP(ldap_state->bind_secret);
660 if (!*credp) {
661 SAFE_FREE(*whop);
662 return LDAP_NO_MEMORY;
664 *methodp = LDAP_AUTH_SIMPLE;
667 GetTimeOfDay(&ldap_state->last_rebind);
669 return 0;
671 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
673 /*******************************************************************
674 a rebind function for authenticated referrals
675 This version takes a void* that we can shove useful stuff in :-)
676 and actually does the connection.
677 ******************************************************************/
678 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
679 static int rebindproc_connect_with_state (LDAP *ldap_struct,
680 LDAP_CONST char *url,
681 ber_tag_t request,
682 ber_int_t msgid, void *arg)
684 struct smbldap_state *ldap_state = arg;
685 int rc;
686 DEBUG(5,("rebindproc_connect_with_state: Rebinding as \"%s\"\n",
687 ldap_state->bind_dn));
689 /** @TODO Should we be doing something to check what servers we rebind to?
690 Could we get a referral to a machine that we don't want to give our
691 username and password to? */
693 rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
695 GetTimeOfDay(&ldap_state->last_rebind);
697 return rc;
699 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
701 /*******************************************************************
702 Add a rebind function for authenticated referrals
703 ******************************************************************/
704 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
705 #else
706 # if LDAP_SET_REBIND_PROC_ARGS == 2
707 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
708 int *method, int freeit )
710 struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
712 return rebindproc_with_state(ldap_struct, whop, credp,
713 method, freeit, ldap_state);
716 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
717 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
719 /*******************************************************************
720 a rebind function for authenticated referrals
721 this also does the connection, but no void*.
722 ******************************************************************/
723 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
724 # if LDAP_SET_REBIND_PROC_ARGS == 2
725 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
726 ber_int_t msgid)
728 struct smbldap_state *ldap_state = smbldap_find_state(ld);
730 return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid,
731 ldap_state);
733 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
734 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
736 /*******************************************************************
737 connect to the ldap server under system privilege.
738 ******************************************************************/
739 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
741 int rc;
742 char *ldap_dn;
743 char *ldap_secret;
744 int version;
746 /* get the password */
747 if (!fetch_ldap_pw(&ldap_dn, &ldap_secret)) {
748 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
749 return LDAP_INVALID_CREDENTIALS;
752 ldap_state->bind_dn = ldap_dn;
753 ldap_state->bind_secret = ldap_secret;
755 /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite
756 (OpenLDAP) doesnt' seem to support it */
758 DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
759 ldap_state->uri, ldap_dn));
761 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
762 # if LDAP_SET_REBIND_PROC_ARGS == 2
763 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect);
764 # endif
765 # if LDAP_SET_REBIND_PROC_ARGS == 3
766 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);
767 # endif
768 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
769 # if LDAP_SET_REBIND_PROC_ARGS == 2
770 ldap_set_rebind_proc(ldap_struct, &rebindproc);
771 # endif
772 # if LDAP_SET_REBIND_PROC_ARGS == 3
773 ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);
774 # endif
775 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
777 rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
779 if (rc != LDAP_SUCCESS) {
780 char *ld_error = NULL;
781 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
782 &ld_error);
783 DEBUG(ldap_state->num_failures ? 2 : 0,
784 ("failed to bind to server %s with dn=\"%s\" Error: %s\n\t%s\n",
785 ldap_state->uri,
786 ldap_dn ? ldap_dn : "(unknown)", ldap_err2string(rc),
787 ld_error ? ld_error : "(unknown)"));
788 SAFE_FREE(ld_error);
789 ldap_state->num_failures++;
790 return rc;
793 ldap_state->num_failures = 0;
794 ldap_state->paged_results = False;
796 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
798 if (smbldap_has_control(ldap_state, ADS_PAGE_CTL_OID) && version == 3) {
799 ldap_state->paged_results = True;
802 DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
803 DEBUGADD(10, ("ldap_connect_system: LDAP server %s support paged results\n",
804 ldap_state->paged_results ? "does" : "does not"));
805 return rc;
808 /**********************************************************************
809 Connect to LDAP server (called before every ldap operation)
810 *********************************************************************/
811 static int smbldap_open(struct smbldap_state *ldap_state)
813 int rc, opt_rc;
814 BOOL reopen = False;
815 SMB_ASSERT(ldap_state);
817 #ifndef NO_LDAP_SECURITY
818 if (geteuid() != 0) {
819 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
820 return LDAP_INSUFFICIENT_ACCESS;
822 #endif
824 if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
826 struct sockaddr_un addr;
827 socklen_t len = sizeof(addr);
828 int sd;
830 opt_rc = ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd);
831 if (opt_rc == 0 && (getpeername(sd, (struct sockaddr *) &addr, &len)) < 0 )
832 reopen = True;
834 #ifdef HAVE_UNIXSOCKET
835 if (opt_rc == 0 && addr.sun_family == AF_UNIX)
836 reopen = True;
837 #endif
838 if (reopen) {
839 /* the other end has died. reopen. */
840 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
841 ldap_state->ldap_struct = NULL;
842 ldap_state->last_ping = (time_t)0;
843 } else {
844 ldap_state->last_ping = time(NULL);
848 if (ldap_state->ldap_struct != NULL) {
849 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
850 return LDAP_SUCCESS;
853 if ((rc = smbldap_open_connection(ldap_state))) {
854 return rc;
857 if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
858 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
859 ldap_state->ldap_struct = NULL;
860 return rc;
864 ldap_state->last_ping = time(NULL);
865 ldap_state->pid = sys_getpid();
866 DEBUG(4,("The LDAP server is succesfully connected\n"));
868 return LDAP_SUCCESS;
871 /**********************************************************************
872 Disconnect from LDAP server
873 *********************************************************************/
874 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
876 if (!ldap_state)
877 return NT_STATUS_INVALID_PARAMETER;
879 if (ldap_state->ldap_struct != NULL) {
880 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
881 ldap_state->ldap_struct = NULL;
884 smbldap_delete_state(ldap_state);
886 DEBUG(5,("The connection to the LDAP server was closed\n"));
887 /* maybe free the results here --metze */
891 return NT_STATUS_OK;
894 static BOOL got_alarm;
896 static void (*old_handler)(int);
898 static void gotalarm_sig(int dummy)
900 got_alarm = True;
903 static int another_ldap_try(struct smbldap_state *ldap_state, int *rc,
904 int *attempts, time_t endtime)
906 time_t now = time(NULL);
907 int open_rc = LDAP_SERVER_DOWN;
909 if (*rc != LDAP_SERVER_DOWN)
910 goto no_next;
912 if (now >= endtime) {
913 smbldap_close(ldap_state);
914 *rc = LDAP_TIMEOUT;
915 goto no_next;
918 if (*attempts == 0) {
919 got_alarm = False;
920 old_handler = CatchSignal(SIGALRM, gotalarm_sig);
921 alarm(endtime - now);
923 if (ldap_state->pid != sys_getpid())
924 smbldap_close(ldap_state);
927 while (1) {
929 if (*attempts != 0)
930 smb_msleep(1000);
932 *attempts += 1;
934 open_rc = smbldap_open(ldap_state);
936 if (open_rc == LDAP_SUCCESS) {
937 ldap_state->last_use = now;
938 return True;
941 if (got_alarm) {
942 *rc = LDAP_TIMEOUT;
943 break;
946 if (open_rc != LDAP_SUCCESS) {
947 DEBUG(1, ("Connection to LDAP server failed for the "
948 "%d try!\n", *attempts));
952 no_next:
953 CatchSignal(SIGALRM, old_handler);
954 alarm(0);
955 ldap_state->last_use = now;
956 return False;
959 /*********************************************************************
960 ********************************************************************/
962 static int smbldap_search_ext(struct smbldap_state *ldap_state,
963 const char *base, int scope, const char *filter,
964 const char *attrs[], int attrsonly,
965 LDAPControl **sctrls, LDAPControl **cctrls,
966 int sizelimit, LDAPMessage **res)
968 int rc = LDAP_SERVER_DOWN;
969 int attempts = 0;
970 char *utf8_filter;
971 time_t endtime = time(NULL)+lp_ldap_timeout();
972 struct timeval timeout;
974 SMB_ASSERT(ldap_state);
976 DEBUG(5,("smbldap_search_ext: base => [%s], filter => [%s], "
977 "scope => [%d]\n", base, filter, scope));
979 if (ldap_state->last_rebind.tv_sec > 0) {
980 struct timeval tval;
981 SMB_BIG_INT tdiff = 0;
982 int sleep_time = 0;
984 ZERO_STRUCT(tval);
985 GetTimeOfDay(&tval);
987 tdiff = usec_time_diff(&tval, &ldap_state->last_rebind);
988 tdiff /= 1000; /* Convert to milliseconds. */
990 sleep_time = lp_ldap_replication_sleep()-(int)tdiff;
991 sleep_time = MIN(sleep_time, MAX_LDAP_REPLICATION_SLEEP_TIME);
993 if (sleep_time > 0) {
994 /* we wait for the LDAP replication */
995 DEBUG(5,("smbldap_search_ext: waiting %d milliseconds "
996 "for LDAP replication.\n",sleep_time));
997 smb_msleep(sleep_time);
998 DEBUG(5,("smbldap_search_ext: go on!\n"));
1000 ZERO_STRUCT(ldap_state->last_rebind);
1003 if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
1004 return LDAP_NO_MEMORY;
1007 /* Setup timeout for the ldap_search_ext_s call - local and remote. */
1008 timeout.tv_sec = lp_ldap_timeout();
1009 timeout.tv_usec = 0;
1011 /* Setup alarm timeout.... Do we need both of these ? JRA.
1012 * Yes, I think we do need both of these. The server timeout only
1013 * covers the case where the server's operation takes too long. It
1014 * does not cover the case where the request hangs on its way to the
1015 * server. The server side timeout is not strictly necessary, it's
1016 * just a bit more kind to the server. VL. */
1018 got_alarm = 0;
1019 CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
1020 alarm(lp_ldap_timeout());
1021 /* End setup timeout. */
1023 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1024 rc = ldap_search_ext_s(ldap_state->ldap_struct, base, scope,
1025 utf8_filter,
1026 CONST_DISCARD(char **, attrs),
1027 attrsonly, sctrls, cctrls, &timeout,
1028 sizelimit, res);
1030 SAFE_FREE(utf8_filter);
1032 /* Teardown timeout. */
1033 CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
1034 alarm(0);
1036 if (got_alarm != 0)
1037 return LDAP_TIMELIMIT_EXCEEDED;
1039 return rc;
1042 int smbldap_search(struct smbldap_state *ldap_state,
1043 const char *base, int scope, const char *filter,
1044 const char *attrs[], int attrsonly,
1045 LDAPMessage **res)
1047 return smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1048 attrsonly, NULL, NULL, LDAP_NO_LIMIT, res);
1051 int smbldap_search_paged(struct smbldap_state *ldap_state,
1052 const char *base, int scope, const char *filter,
1053 const char **attrs, int attrsonly, int pagesize,
1054 LDAPMessage **res, void **cookie)
1056 LDAPControl pr;
1057 LDAPControl **rcontrols;
1058 LDAPControl *controls[2] = { NULL, NULL};
1059 BerElement *cookie_be = NULL;
1060 struct berval *cookie_bv = NULL;
1061 int tmp = 0, i, rc;
1062 BOOL critical = True;
1064 *res = NULL;
1066 DEBUG(3,("smbldap_search_paged: base => [%s], filter => [%s],"
1067 "scope => [%d], pagesize => [%d]\n",
1068 base, filter, scope, pagesize));
1070 cookie_be = ber_alloc_t(LBER_USE_DER);
1071 if (cookie_be == NULL) {
1072 DEBUG(0,("smbldap_create_page_control: ber_alloc_t returns "
1073 "NULL\n"));
1074 return LDAP_NO_MEMORY;
1077 /* construct cookie */
1078 if (*cookie != NULL) {
1079 ber_printf(cookie_be, "{iO}", (ber_int_t) pagesize, *cookie);
1080 ber_bvfree(*cookie); /* don't need it from last time */
1081 *cookie = NULL;
1082 } else {
1083 ber_printf(cookie_be, "{io}", (ber_int_t) pagesize, "", 0);
1085 ber_flatten(cookie_be, &cookie_bv);
1087 pr.ldctl_oid = CONST_DISCARD(char *, ADS_PAGE_CTL_OID);
1088 pr.ldctl_iscritical = (char) critical;
1089 pr.ldctl_value.bv_len = cookie_bv->bv_len;
1090 pr.ldctl_value.bv_val = cookie_bv->bv_val;
1092 controls[0] = &pr;
1093 controls[1] = NULL;
1095 rc = smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1096 0, controls, NULL, LDAP_NO_LIMIT, res);
1098 ber_free(cookie_be, 1);
1099 ber_bvfree(cookie_bv);
1101 if (rc != 0) {
1102 DEBUG(3,("smbldap_search_paged: smbldap_search_ext(%s) "
1103 "failed with [%s]\n", filter, ldap_err2string(rc)));
1104 goto done;
1107 DEBUG(3,("smbldap_search_paged: search was successfull\n"));
1109 rc = ldap_parse_result(ldap_state->ldap_struct, *res, NULL, NULL,
1110 NULL, NULL, &rcontrols, 0);
1111 if (rc != 0) {
1112 DEBUG(3,("smbldap_search_paged: ldap_parse_result failed " \
1113 "with [%s]\n", ldap_err2string(rc)));
1114 goto done;
1117 if (rcontrols == NULL)
1118 goto done;
1120 for (i=0; rcontrols[i]; i++) {
1122 if (strcmp(ADS_PAGE_CTL_OID, rcontrols[i]->ldctl_oid) != 0)
1123 continue;
1125 cookie_be = ber_init(&rcontrols[i]->ldctl_value);
1126 ber_scanf(cookie_be,"{iO}", &tmp, &cookie_bv);
1127 /* the berval is the cookie, but must be freed when it is all
1128 done */
1129 if (cookie_bv->bv_len)
1130 *cookie=ber_bvdup(cookie_bv);
1131 else
1132 *cookie=NULL;
1133 ber_bvfree(cookie_bv);
1134 ber_free(cookie_be, 1);
1135 break;
1137 ldap_controls_free(rcontrols);
1138 done:
1139 return rc;
1142 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1144 int rc = LDAP_SERVER_DOWN;
1145 int attempts = 0;
1146 char *utf8_dn;
1147 time_t endtime = time(NULL)+lp_ldap_timeout();
1149 SMB_ASSERT(ldap_state);
1151 DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1153 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1154 return LDAP_NO_MEMORY;
1157 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1158 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1160 SAFE_FREE(utf8_dn);
1161 return rc;
1164 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1166 int rc = LDAP_SERVER_DOWN;
1167 int attempts = 0;
1168 char *utf8_dn;
1169 time_t endtime = time(NULL)+lp_ldap_timeout();
1171 SMB_ASSERT(ldap_state);
1173 DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1175 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1176 return LDAP_NO_MEMORY;
1179 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1180 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1182 SAFE_FREE(utf8_dn);
1183 return rc;
1186 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1188 int rc = LDAP_SERVER_DOWN;
1189 int attempts = 0;
1190 char *utf8_dn;
1191 time_t endtime = time(NULL)+lp_ldap_timeout();
1193 SMB_ASSERT(ldap_state);
1195 DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1197 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1198 return LDAP_NO_MEMORY;
1201 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1202 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1204 SAFE_FREE(utf8_dn);
1205 return rc;
1208 int smbldap_extended_operation(struct smbldap_state *ldap_state,
1209 LDAP_CONST char *reqoid, struct berval *reqdata,
1210 LDAPControl **serverctrls, LDAPControl **clientctrls,
1211 char **retoidp, struct berval **retdatap)
1213 int rc = LDAP_SERVER_DOWN;
1214 int attempts = 0;
1215 time_t endtime = time(NULL)+lp_ldap_timeout();
1217 if (!ldap_state)
1218 return (-1);
1220 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1221 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid,
1222 reqdata, serverctrls,
1223 clientctrls, retoidp, retdatap);
1224 return rc;
1227 /*******************************************************************
1228 run the search by name.
1229 ******************************************************************/
1230 int smbldap_search_suffix (struct smbldap_state *ldap_state, const char *filter,
1231 const char **search_attr, LDAPMessage ** result)
1233 int scope = LDAP_SCOPE_SUBTREE;
1234 int rc;
1236 rc = smbldap_search(ldap_state, lp_ldap_suffix(), scope, filter, search_attr, 0, result);
1238 if (rc != LDAP_SUCCESS) {
1239 char *ld_error = NULL;
1240 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1241 &ld_error);
1242 DEBUG(0,("smbldap_search_suffix: Problem during the LDAP search: %s (%s)\n",
1243 ld_error?ld_error:"(unknown)", ldap_err2string (rc)));
1244 SAFE_FREE(ld_error);
1247 return rc;
1250 static void smbldap_idle_fn(void **data, time_t *interval, time_t now)
1252 struct smbldap_state *state = (struct smbldap_state *)(*data);
1254 if (state->ldap_struct == NULL) {
1255 DEBUG(10,("ldap connection not connected...\n"));
1256 return;
1259 if ((state->last_use+SMBLDAP_IDLE_TIME) > now) {
1260 DEBUG(10,("ldap connection not idle...\n"));
1261 return;
1264 DEBUG(7,("ldap connection idle...closing connection\n"));
1265 smbldap_close(state);
1268 /**********************************************************************
1269 Housekeeping
1270 *********************************************************************/
1272 void smbldap_free_struct(struct smbldap_state **ldap_state)
1274 smbldap_close(*ldap_state);
1276 if ((*ldap_state)->bind_secret) {
1277 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1280 SAFE_FREE((*ldap_state)->bind_dn);
1281 SAFE_FREE((*ldap_state)->bind_secret);
1283 smb_unregister_idle_event((*ldap_state)->event_id);
1285 *ldap_state = NULL;
1287 /* No need to free any further, as it is talloc()ed */
1291 /**********************************************************************
1292 Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1293 *********************************************************************/
1295 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state)
1297 *smbldap_state = TALLOC_ZERO_P(mem_ctx, struct smbldap_state);
1298 if (!*smbldap_state) {
1299 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1300 return NT_STATUS_NO_MEMORY;
1303 if (location) {
1304 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1305 } else {
1306 (*smbldap_state)->uri = "ldap://localhost";
1309 (*smbldap_state)->event_id =
1310 smb_register_idle_event(smbldap_idle_fn, (void *)(*smbldap_state),
1311 SMBLDAP_IDLE_TIME);
1313 if ((*smbldap_state)->event_id == SMB_EVENT_ID_INVALID) {
1314 DEBUG(0,("Failed to register LDAP idle event!\n"));
1315 return NT_STATUS_INVALID_HANDLE;
1318 return NT_STATUS_OK;
1321 /*******************************************************************
1322 Return a copy of the DN for a LDAPMessage. Convert from utf8 to CH_UNIX.
1323 ********************************************************************/
1325 char *smbldap_get_dn(LDAP *ld, LDAPMessage *entry)
1327 char *utf8_dn, *unix_dn;
1329 utf8_dn = ldap_get_dn(ld, entry);
1330 if (!utf8_dn) {
1331 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1332 return NULL;
1334 if (pull_utf8_allocate(&unix_dn, utf8_dn) == (size_t)-1) {
1335 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 [%s]\n", utf8_dn));
1336 return NULL;
1338 ldap_memfree(utf8_dn);
1339 return unix_dn;
1342 /*******************************************************************
1343 Check if root-dse has a certain Control or Extension
1344 ********************************************************************/
1346 static BOOL smbldap_check_root_dse(struct smbldap_state *ldap_state, const char **attrs, const char *value)
1348 LDAPMessage *msg = NULL;
1349 LDAPMessage *entry = NULL;
1350 char **values = NULL;
1351 int rc, num_result, num_values, i;
1352 BOOL result = False;
1354 if (!attrs[0]) {
1355 DEBUG(3,("smbldap_check_root_dse: nothing to look for\n"));
1356 return False;
1359 if (!strequal(attrs[0], "supportedExtension") &&
1360 !strequal(attrs[0], "supportedControl") &&
1361 !strequal(attrs[0], "namingContexts")) {
1362 DEBUG(3,("smbldap_check_root_dse: no idea what to query root-dse for: %s ?\n", attrs[0]));
1363 return False;
1366 rc = ldap_search_s(ldap_state->ldap_struct, "", LDAP_SCOPE_BASE,
1367 "(objectclass=*)", attrs, 0 , &msg);
1369 if (rc != LDAP_SUCCESS) {
1370 DEBUG(3,("smbldap_check_root_dse: Could not search rootDSE\n"));
1371 return False;
1374 num_result = ldap_count_entries(ldap_state->ldap_struct, msg);
1376 if (num_result != 1) {
1377 DEBUG(3,("smbldap_check_root_dse: Expected one rootDSE, got %d\n", num_result));
1378 goto done;
1381 entry = ldap_first_entry(ldap_state->ldap_struct, msg);
1383 if (entry == NULL) {
1384 DEBUG(3,("smbldap_check_root_dse: Could not retrieve rootDSE\n"));
1385 goto done;
1388 values = ldap_get_values(ldap_state->ldap_struct, entry, attrs[0]);
1390 if (values == NULL) {
1391 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not support any %s\n", attrs[0]));
1392 goto done;
1395 num_values = ldap_count_values(values);
1397 if (num_values == 0) {
1398 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not have any %s\n", attrs[0]));
1399 goto done;
1402 for (i=0; i<num_values; i++) {
1403 if (strcmp(values[i], value) == 0)
1404 result = True;
1408 done:
1409 if (values != NULL)
1410 ldap_value_free(values);
1411 if (msg != NULL)
1412 ldap_msgfree(msg);
1414 return result;
1418 /*******************************************************************
1419 Check if LDAP-Server supports a certain Control (OID in string format)
1420 ********************************************************************/
1422 BOOL smbldap_has_control(struct smbldap_state *ldap_state, const char *control)
1424 const char *attrs[] = { "supportedControl", NULL };
1425 return smbldap_check_root_dse(ldap_state, attrs, control);
1428 /*******************************************************************
1429 Check if LDAP-Server supports a certain Extension (OID in string format)
1430 ********************************************************************/
1432 BOOL smbldap_has_extension(struct smbldap_state *ldap_state, const char *extension)
1434 const char *attrs[] = { "supportedExtension", NULL };
1435 return smbldap_check_root_dse(ldap_state, attrs, extension);
1438 /*******************************************************************
1439 Check if LDAP-Server holds a given namingContext
1440 ********************************************************************/
1442 BOOL smbldap_has_naming_context(struct smbldap_state *ldap_state, const char *naming_context)
1444 const char *attrs[] = { "namingContexts", NULL };
1445 return smbldap_check_root_dse(ldap_state, attrs, naming_context);