s3/ldap: use monotonic clock for timeouts in smbldap
[Samba/gebeck_regimport.git] / source3 / lib / smbldap.c
blob67e3d4dc1b17e5d8be84fdabd5f578ffa2af0fdf
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 3 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, see <http://www.gnu.org/licenses/>.
25 #include "includes.h"
26 #include "smbldap.h"
27 #include "secrets.h"
29 /* Try not to hit the up or down server forever */
31 #define SMBLDAP_DONT_PING_TIME 10 /* ping only all 10 seconds */
32 #define SMBLDAP_NUM_RETRIES 8 /* retry only 8 times */
34 #define SMBLDAP_IDLE_TIME 150 /* After 2.5 minutes disconnect */
37 /* attributes used by Samba 2.2 */
39 ATTRIB_MAP_ENTRY attrib_map_v22[] = {
40 { LDAP_ATTR_UID, "uid" },
41 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
42 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
43 { LDAP_ATTR_UNIX_HOME, "homeDirectory" },
44 { LDAP_ATTR_PWD_LAST_SET, "pwdLastSet" },
45 { LDAP_ATTR_PWD_CAN_CHANGE, "pwdCanChange" },
46 { LDAP_ATTR_PWD_MUST_CHANGE, "pwdMustChange" },
47 { LDAP_ATTR_LOGON_TIME, "logonTime" },
48 { LDAP_ATTR_LOGOFF_TIME, "logoffTime" },
49 { LDAP_ATTR_KICKOFF_TIME, "kickoffTime" },
50 { LDAP_ATTR_CN, "cn" },
51 { LDAP_ATTR_SN, "sn" },
52 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
53 { LDAP_ATTR_HOME_PATH, "smbHome" },
54 { LDAP_ATTR_HOME_DRIVE, "homeDrive" },
55 { LDAP_ATTR_LOGON_SCRIPT, "scriptPath" },
56 { LDAP_ATTR_PROFILE_PATH, "profilePath" },
57 { LDAP_ATTR_DESC, "description" },
58 { LDAP_ATTR_USER_WKS, "userWorkstations"},
59 { LDAP_ATTR_USER_RID, "rid" },
60 { LDAP_ATTR_PRIMARY_GROUP_RID, "primaryGroupID"},
61 { LDAP_ATTR_LMPW, "lmPassword" },
62 { LDAP_ATTR_NTPW, "ntPassword" },
63 { LDAP_ATTR_DOMAIN, "domain" },
64 { LDAP_ATTR_OBJCLASS, "objectClass" },
65 { LDAP_ATTR_ACB_INFO, "acctFlags" },
66 { LDAP_ATTR_MOD_TIMESTAMP, "modifyTimestamp" },
67 { LDAP_ATTR_LIST_END, NULL }
70 ATTRIB_MAP_ENTRY attrib_map_to_delete_v22[] = {
71 { LDAP_ATTR_PWD_LAST_SET, "pwdLastSet" },
72 { LDAP_ATTR_PWD_CAN_CHANGE, "pwdCanChange" },
73 { LDAP_ATTR_PWD_MUST_CHANGE, "pwdMustChange" },
74 { LDAP_ATTR_LOGON_TIME, "logonTime" },
75 { LDAP_ATTR_LOGOFF_TIME, "logoffTime" },
76 { LDAP_ATTR_KICKOFF_TIME, "kickoffTime" },
77 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
78 { LDAP_ATTR_HOME_PATH, "smbHome" },
79 { LDAP_ATTR_HOME_DRIVE, "homeDrives" },
80 { LDAP_ATTR_LOGON_SCRIPT, "scriptPath" },
81 { LDAP_ATTR_PROFILE_PATH, "profilePath" },
82 { LDAP_ATTR_USER_WKS, "userWorkstations"},
83 { LDAP_ATTR_USER_RID, "rid" },
84 { LDAP_ATTR_PRIMARY_GROUP_RID, "primaryGroupID"},
85 { LDAP_ATTR_LMPW, "lmPassword" },
86 { LDAP_ATTR_NTPW, "ntPassword" },
87 { LDAP_ATTR_DOMAIN, "domain" },
88 { LDAP_ATTR_ACB_INFO, "acctFlags" },
89 { LDAP_ATTR_LIST_END, NULL }
92 /* attributes used by Samba 3.0's sambaSamAccount */
94 ATTRIB_MAP_ENTRY attrib_map_v30[] = {
95 { LDAP_ATTR_UID, "uid" },
96 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
97 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
98 { LDAP_ATTR_UNIX_HOME, "homeDirectory" },
99 { LDAP_ATTR_PWD_LAST_SET, "sambaPwdLastSet" },
100 { LDAP_ATTR_PWD_CAN_CHANGE, "sambaPwdCanChange" },
101 { LDAP_ATTR_PWD_MUST_CHANGE, "sambaPwdMustChange" },
102 { LDAP_ATTR_LOGON_TIME, "sambaLogonTime" },
103 { LDAP_ATTR_LOGOFF_TIME, "sambaLogoffTime" },
104 { LDAP_ATTR_KICKOFF_TIME, "sambaKickoffTime" },
105 { LDAP_ATTR_CN, "cn" },
106 { LDAP_ATTR_SN, "sn" },
107 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
108 { LDAP_ATTR_HOME_DRIVE, "sambaHomeDrive" },
109 { LDAP_ATTR_HOME_PATH, "sambaHomePath" },
110 { LDAP_ATTR_LOGON_SCRIPT, "sambaLogonScript" },
111 { LDAP_ATTR_PROFILE_PATH, "sambaProfilePath" },
112 { LDAP_ATTR_DESC, "description" },
113 { LDAP_ATTR_USER_WKS, "sambaUserWorkstations" },
114 { LDAP_ATTR_USER_SID, LDAP_ATTRIBUTE_SID },
115 { LDAP_ATTR_PRIMARY_GROUP_SID, "sambaPrimaryGroupSID" },
116 { LDAP_ATTR_LMPW, "sambaLMPassword" },
117 { LDAP_ATTR_NTPW, "sambaNTPassword" },
118 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
119 { LDAP_ATTR_OBJCLASS, "objectClass" },
120 { LDAP_ATTR_ACB_INFO, "sambaAcctFlags" },
121 { LDAP_ATTR_MUNGED_DIAL, "sambaMungedDial" },
122 { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
123 { LDAP_ATTR_BAD_PASSWORD_TIME, "sambaBadPasswordTime" },
124 { LDAP_ATTR_PWD_HISTORY, "sambaPasswordHistory" },
125 { LDAP_ATTR_MOD_TIMESTAMP, "modifyTimestamp" },
126 { LDAP_ATTR_LOGON_HOURS, "sambaLogonHours" },
127 { LDAP_ATTR_LIST_END, NULL }
130 ATTRIB_MAP_ENTRY attrib_map_to_delete_v30[] = {
131 { LDAP_ATTR_PWD_LAST_SET, "sambaPwdLastSet" },
132 { LDAP_ATTR_PWD_CAN_CHANGE, "sambaPwdCanChange" },
133 { LDAP_ATTR_PWD_MUST_CHANGE, "sambaPwdMustChange" },
134 { LDAP_ATTR_LOGON_TIME, "sambaLogonTime" },
135 { LDAP_ATTR_LOGOFF_TIME, "sambaLogoffTime" },
136 { LDAP_ATTR_KICKOFF_TIME, "sambaKickoffTime" },
137 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
138 { LDAP_ATTR_HOME_DRIVE, "sambaHomeDrive" },
139 { LDAP_ATTR_HOME_PATH, "sambaHomePath" },
140 { LDAP_ATTR_LOGON_SCRIPT, "sambaLogonScript" },
141 { LDAP_ATTR_PROFILE_PATH, "sambaProfilePath" },
142 { LDAP_ATTR_USER_WKS, "sambaUserWorkstations" },
143 { LDAP_ATTR_USER_SID, LDAP_ATTRIBUTE_SID },
144 { LDAP_ATTR_PRIMARY_GROUP_SID, "sambaPrimaryGroupSID" },
145 { LDAP_ATTR_LMPW, "sambaLMPassword" },
146 { LDAP_ATTR_NTPW, "sambaNTPassword" },
147 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
148 { LDAP_ATTR_ACB_INFO, "sambaAcctFlags" },
149 { LDAP_ATTR_MUNGED_DIAL, "sambaMungedDial" },
150 { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
151 { LDAP_ATTR_BAD_PASSWORD_TIME, "sambaBadPasswordTime" },
152 { LDAP_ATTR_PWD_HISTORY, "sambaPasswordHistory" },
153 { LDAP_ATTR_LOGON_HOURS, "sambaLogonHours" },
154 { LDAP_ATTR_LIST_END, NULL }
157 /* attributes used for allocating RIDs */
159 ATTRIB_MAP_ENTRY dominfo_attr_list[] = {
160 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
161 { LDAP_ATTR_NEXT_RID, "sambaNextRid" },
162 { LDAP_ATTR_NEXT_USERRID, "sambaNextUserRid" },
163 { LDAP_ATTR_NEXT_GROUPRID, "sambaNextGroupRid" },
164 { LDAP_ATTR_DOM_SID, LDAP_ATTRIBUTE_SID },
165 { LDAP_ATTR_ALGORITHMIC_RID_BASE,"sambaAlgorithmicRidBase"},
166 { LDAP_ATTR_OBJCLASS, "objectClass" },
167 { LDAP_ATTR_LIST_END, NULL },
170 /* Samba 3.0 group mapping attributes */
172 ATTRIB_MAP_ENTRY groupmap_attr_list[] = {
173 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
174 { LDAP_ATTR_GROUP_SID, LDAP_ATTRIBUTE_SID },
175 { LDAP_ATTR_GROUP_TYPE, "sambaGroupType" },
176 { LDAP_ATTR_SID_LIST, "sambaSIDList" },
177 { LDAP_ATTR_DESC, "description" },
178 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
179 { LDAP_ATTR_CN, "cn" },
180 { LDAP_ATTR_OBJCLASS, "objectClass" },
181 { LDAP_ATTR_LIST_END, NULL }
184 ATTRIB_MAP_ENTRY groupmap_attr_list_to_delete[] = {
185 { LDAP_ATTR_GROUP_SID, LDAP_ATTRIBUTE_SID },
186 { LDAP_ATTR_GROUP_TYPE, "sambaGroupType" },
187 { LDAP_ATTR_DESC, "description" },
188 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
189 { LDAP_ATTR_SID_LIST, "sambaSIDList" },
190 { LDAP_ATTR_LIST_END, NULL }
193 /* idmap_ldap sambaUnixIdPool */
195 ATTRIB_MAP_ENTRY idpool_attr_list[] = {
196 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
197 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
198 { LDAP_ATTR_OBJCLASS, "objectClass" },
199 { LDAP_ATTR_LIST_END, NULL }
202 ATTRIB_MAP_ENTRY sidmap_attr_list[] = {
203 { LDAP_ATTR_SID, LDAP_ATTRIBUTE_SID },
204 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
205 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
206 { LDAP_ATTR_OBJCLASS, "objectClass" },
207 { LDAP_ATTR_LIST_END, NULL }
210 /**********************************************************************
211 perform a simple table lookup and return the attribute name
212 **********************************************************************/
214 const char* get_attr_key2string( ATTRIB_MAP_ENTRY table[], int key )
216 int i = 0;
218 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
219 if ( table[i].attrib == key )
220 return table[i].name;
221 i++;
224 return NULL;
228 /**********************************************************************
229 Return the list of attribute names from a mapping table
230 **********************************************************************/
232 const char** get_attr_list( TALLOC_CTX *mem_ctx, ATTRIB_MAP_ENTRY table[] )
234 const char **names;
235 int i = 0;
237 while ( table[i].attrib != LDAP_ATTR_LIST_END )
238 i++;
239 i++;
241 names = TALLOC_ARRAY( mem_ctx, const char*, i );
242 if ( !names ) {
243 DEBUG(0,("get_attr_list: out of memory\n"));
244 return NULL;
247 i = 0;
248 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
249 names[i] = talloc_strdup( names, table[i].name );
250 i++;
252 names[i] = NULL;
254 return names;
257 /*******************************************************************
258 Search an attribute and return the first value found.
259 ******************************************************************/
261 bool smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
262 const char *attribute, char *value,
263 int max_len)
265 char **values;
267 if ( !attribute )
268 return False;
270 value[0] = '\0';
272 if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
273 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
275 return False;
278 if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, max_len, False) == (size_t)-1) {
279 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n",
280 attribute, values[0]));
281 ldap_value_free(values);
282 return False;
285 ldap_value_free(values);
286 #ifdef DEBUG_PASSWORDS
287 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
288 #endif
289 return True;
292 char * smbldap_talloc_single_attribute(LDAP *ldap_struct, LDAPMessage *entry,
293 const char *attribute,
294 TALLOC_CTX *mem_ctx)
296 char **values;
297 char *result;
298 size_t converted_size;
300 if (attribute == NULL) {
301 return NULL;
304 values = ldap_get_values(ldap_struct, entry, attribute);
306 if (values == NULL) {
307 DEBUG(10, ("attribute %s does not exist\n", attribute));
308 return NULL;
311 if (ldap_count_values(values) != 1) {
312 DEBUG(10, ("attribute %s has %d values, expected only one\n",
313 attribute, ldap_count_values(values)));
314 ldap_value_free(values);
315 return NULL;
318 if (!pull_utf8_talloc(mem_ctx, &result, values[0], &converted_size)) {
319 DEBUG(10, ("pull_utf8_talloc failed\n"));
320 ldap_value_free(values);
321 return NULL;
324 ldap_value_free(values);
326 #ifdef DEBUG_PASSWORDS
327 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n",
328 attribute, result));
329 #endif
330 return result;
333 char * smbldap_talloc_first_attribute(LDAP *ldap_struct, LDAPMessage *entry,
334 const char *attribute,
335 TALLOC_CTX *mem_ctx)
337 char **values;
338 char *result;
339 size_t converted_size;
341 if (attribute == NULL) {
342 return NULL;
345 values = ldap_get_values(ldap_struct, entry, attribute);
347 if (values == NULL) {
348 DEBUG(10, ("attribute %s does not exist\n", attribute));
349 return NULL;
352 if (!pull_utf8_talloc(mem_ctx, &result, values[0], &converted_size)) {
353 DEBUG(10, ("pull_utf8_talloc failed\n"));
354 ldap_value_free(values);
355 return NULL;
358 ldap_value_free(values);
360 #ifdef DEBUG_PASSWORDS
361 DEBUG (100, ("smbldap_get_first_attribute: [%s] = [%s]\n",
362 attribute, result));
363 #endif
364 return result;
367 char * smbldap_talloc_smallest_attribute(LDAP *ldap_struct, LDAPMessage *entry,
368 const char *attribute,
369 TALLOC_CTX *mem_ctx)
371 char **values;
372 char *result;
373 size_t converted_size;
374 int i, num_values;
376 if (attribute == NULL) {
377 return NULL;
380 values = ldap_get_values(ldap_struct, entry, attribute);
382 if (values == NULL) {
383 DEBUG(10, ("attribute %s does not exist\n", attribute));
384 return NULL;
387 if (!pull_utf8_talloc(mem_ctx, &result, values[0], &converted_size)) {
388 DEBUG(10, ("pull_utf8_talloc failed\n"));
389 ldap_value_free(values);
390 return NULL;
393 num_values = ldap_count_values(values);
395 for (i=1; i<num_values; i++) {
396 char *tmp;
398 if (!pull_utf8_talloc(mem_ctx, &tmp, values[i],
399 &converted_size)) {
400 DEBUG(10, ("pull_utf8_talloc failed\n"));
401 TALLOC_FREE(result);
402 ldap_value_free(values);
403 return NULL;
406 if (StrCaseCmp(tmp, result) < 0) {
407 TALLOC_FREE(result);
408 result = tmp;
409 } else {
410 TALLOC_FREE(tmp);
414 ldap_value_free(values);
416 #ifdef DEBUG_PASSWORDS
417 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n",
418 attribute, result));
419 #endif
420 return result;
423 bool smbldap_talloc_single_blob(TALLOC_CTX *mem_ctx, LDAP *ld,
424 LDAPMessage *msg, const char *attrib,
425 DATA_BLOB *blob)
427 struct berval **values;
429 values = ldap_get_values_len(ld, msg, attrib);
430 if (!values) {
431 return false;
434 if (ldap_count_values_len(values) != 1) {
435 DEBUG(10, ("Expected one value for %s, got %d\n", attrib,
436 ldap_count_values_len(values)));
437 return false;
440 *blob = data_blob_talloc(mem_ctx, values[0]->bv_val,
441 values[0]->bv_len);
442 ldap_value_free_len(values);
444 return (blob->data != NULL);
447 bool smbldap_pull_sid(LDAP *ld, LDAPMessage *msg, const char *attrib,
448 struct dom_sid *sid)
450 DATA_BLOB blob;
451 bool ret;
453 if (!smbldap_talloc_single_blob(talloc_tos(), ld, msg, attrib,
454 &blob)) {
455 return false;
457 ret = sid_parse((char *)blob.data, blob.length, sid);
458 TALLOC_FREE(blob.data);
459 return ret;
462 static int ldapmsg_destructor(LDAPMessage **result) {
463 ldap_msgfree(*result);
464 return 0;
467 void talloc_autofree_ldapmsg(TALLOC_CTX *mem_ctx, LDAPMessage *result)
469 LDAPMessage **handle;
471 if (result == NULL) {
472 return;
475 handle = TALLOC_P(mem_ctx, LDAPMessage *);
476 SMB_ASSERT(handle != NULL);
478 *handle = result;
479 talloc_set_destructor(handle, ldapmsg_destructor);
482 static int ldapmod_destructor(LDAPMod ***mod) {
483 ldap_mods_free(*mod, True);
484 return 0;
487 void talloc_autofree_ldapmod(TALLOC_CTX *mem_ctx, LDAPMod **mod)
489 LDAPMod ***handle;
491 if (mod == NULL) {
492 return;
495 handle = TALLOC_P(mem_ctx, LDAPMod **);
496 SMB_ASSERT(handle != NULL);
498 *handle = mod;
499 talloc_set_destructor(handle, ldapmod_destructor);
502 /************************************************************************
503 Routine to manage the LDAPMod structure array
504 manage memory used by the array, by each struct, and values
505 ***********************************************************************/
507 void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
509 LDAPMod **mods;
510 int i;
511 int j;
513 mods = *modlist;
515 /* sanity checks on the mod values */
517 if (attribute == NULL || *attribute == '\0') {
518 return;
521 #if 0 /* commented out after discussion with abartlet. Do not reenable.
522 left here so other do not re-add similar code --jerry */
523 if (value == NULL || *value == '\0')
524 return;
525 #endif
527 if (mods == NULL) {
528 mods = SMB_MALLOC_P(LDAPMod *);
529 if (mods == NULL) {
530 smb_panic("smbldap_set_mod: out of memory!");
531 /* notreached. */
533 mods[0] = NULL;
536 for (i = 0; mods[i] != NULL; ++i) {
537 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
538 break;
541 if (mods[i] == NULL) {
542 mods = SMB_REALLOC_ARRAY (mods, LDAPMod *, i + 2);
543 if (mods == NULL) {
544 smb_panic("smbldap_set_mod: out of memory!");
545 /* notreached. */
547 mods[i] = SMB_MALLOC_P(LDAPMod);
548 if (mods[i] == NULL) {
549 smb_panic("smbldap_set_mod: out of memory!");
550 /* notreached. */
552 mods[i]->mod_op = modop;
553 mods[i]->mod_values = NULL;
554 mods[i]->mod_type = SMB_STRDUP(attribute);
555 mods[i + 1] = NULL;
558 if (value != NULL) {
559 char *utf8_value = NULL;
560 size_t converted_size;
562 j = 0;
563 if (mods[i]->mod_values != NULL) {
564 for (; mods[i]->mod_values[j] != NULL; j++);
566 mods[i]->mod_values = SMB_REALLOC_ARRAY(mods[i]->mod_values, char *, j + 2);
568 if (mods[i]->mod_values == NULL) {
569 smb_panic("smbldap_set_mod: out of memory!");
570 /* notreached. */
573 if (!push_utf8_talloc(talloc_tos(), &utf8_value, value, &converted_size)) {
574 smb_panic("smbldap_set_mod: String conversion failure!");
575 /* notreached. */
578 mods[i]->mod_values[j] = SMB_STRDUP(utf8_value);
579 TALLOC_FREE(utf8_value);
580 SMB_ASSERT(mods[i]->mod_values[j] != NULL);
582 mods[i]->mod_values[j + 1] = NULL;
584 *modlist = mods;
587 /**********************************************************************
588 Set attribute to newval in LDAP, regardless of what value the
589 attribute had in LDAP before.
590 *********************************************************************/
592 void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
593 LDAPMod ***mods,
594 const char *attribute, const char *newval)
596 char oldval[2048]; /* current largest allowed value is mungeddial */
597 bool existed;
599 if (attribute == NULL) {
600 /* This can actually happen for ldapsam_compat where we for
601 * example don't have a password history */
602 return;
605 if (existing != NULL) {
606 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval, sizeof(oldval));
607 } else {
608 existed = False;
609 *oldval = '\0';
612 /* all of our string attributes are case insensitive */
614 if (existed && newval && (StrCaseCmp(oldval, newval) == 0)) {
616 /* Believe it or not, but LDAP will deny a delete and
617 an add at the same time if the values are the
618 same... */
619 DEBUG(10,("smbldap_make_mod: attribute |%s| not changed.\n", attribute));
620 return;
623 if (existed) {
624 /* There has been no value before, so don't delete it.
625 * Here's a possible race: We might end up with
626 * duplicate attributes */
627 /* By deleting exactly the value we found in the entry this
628 * should be race-free in the sense that the LDAP-Server will
629 * deny the complete operation if somebody changed the
630 * attribute behind our back. */
631 /* This will also allow modifying single valued attributes
632 * in Novell NDS. In NDS you have to first remove attribute and then
633 * you could add new value */
635 DEBUG(10,("smbldap_make_mod: deleting attribute |%s| values |%s|\n", attribute, oldval));
636 smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, oldval);
639 /* Regardless of the real operation (add or modify)
640 we add the new value here. We rely on deleting
641 the old value, should it exist. */
643 if ((newval != NULL) && (strlen(newval) > 0)) {
644 DEBUG(10,("smbldap_make_mod: adding attribute |%s| value |%s|\n", attribute, newval));
645 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
649 /**********************************************************************
650 Some varients of the LDAP rebind code do not pass in the third 'arg'
651 pointer to a void*, so we try and work around it by assuming that the
652 value of the 'LDAP *' pointer is the same as the one we had passed in
653 **********************************************************************/
655 struct smbldap_state_lookup {
656 LDAP *ld;
657 struct smbldap_state *smbldap_state;
658 struct smbldap_state_lookup *prev, *next;
661 static struct smbldap_state_lookup *smbldap_state_lookup_list;
663 static struct smbldap_state *smbldap_find_state(LDAP *ld)
665 struct smbldap_state_lookup *t;
667 for (t = smbldap_state_lookup_list; t; t = t->next) {
668 if (t->ld == ld) {
669 return t->smbldap_state;
672 return NULL;
675 static void smbldap_delete_state(struct smbldap_state *smbldap_state)
677 struct smbldap_state_lookup *t;
679 for (t = smbldap_state_lookup_list; t; t = t->next) {
680 if (t->smbldap_state == smbldap_state) {
681 DLIST_REMOVE(smbldap_state_lookup_list, t);
682 SAFE_FREE(t);
683 return;
688 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state)
690 struct smbldap_state *tmp_ldap_state;
691 struct smbldap_state_lookup *t;
693 if ((tmp_ldap_state = smbldap_find_state(ld))) {
694 SMB_ASSERT(tmp_ldap_state == smbldap_state);
695 return;
698 t = SMB_XMALLOC_P(struct smbldap_state_lookup);
699 ZERO_STRUCTP(t);
701 DLIST_ADD_END(smbldap_state_lookup_list, t, struct smbldap_state_lookup *);
702 t->ld = ld;
703 t->smbldap_state = smbldap_state;
706 /********************************************************************
707 start TLS on an existing LDAP connection
708 *******************************************************************/
710 int smb_ldap_start_tls(LDAP *ldap_struct, int version)
712 #ifdef LDAP_OPT_X_TLS
713 int rc;
714 #endif
716 if (lp_ldap_ssl() != LDAP_SSL_START_TLS) {
717 return LDAP_SUCCESS;
720 #ifdef LDAP_OPT_X_TLS
721 if (version != LDAP_VERSION3) {
722 DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
723 return LDAP_OPERATIONS_ERROR;
726 if ((rc = ldap_start_tls_s (ldap_struct, NULL, NULL)) != LDAP_SUCCESS) {
727 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
728 ldap_err2string(rc)));
729 return rc;
732 DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
733 return LDAP_SUCCESS;
734 #else
735 DEBUG(0,("StartTLS not supported by LDAP client libraries!\n"));
736 return LDAP_OPERATIONS_ERROR;
737 #endif
740 /********************************************************************
741 setup a connection to the LDAP server based on a uri
742 *******************************************************************/
744 static int smb_ldap_setup_conn(LDAP **ldap_struct, const char *uri)
746 int rc;
748 DEBUG(10, ("smb_ldap_setup_connection: %s\n", uri));
750 #ifdef HAVE_LDAP_INITIALIZE
752 rc = ldap_initialize(ldap_struct, uri);
753 if (rc) {
754 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
755 return rc;
758 if (lp_ldap_follow_referral() != Auto) {
759 rc = ldap_set_option(*ldap_struct, LDAP_OPT_REFERRALS,
760 lp_ldap_follow_referral() ? LDAP_OPT_ON : LDAP_OPT_OFF);
761 if (rc != LDAP_SUCCESS)
762 DEBUG(0, ("Failed to set LDAP_OPT_REFERRALS: %s\n",
763 ldap_err2string(rc)));
766 return LDAP_SUCCESS;
767 #else
769 /* Parse the string manually */
772 int port = 0;
773 fstring protocol;
774 fstring host;
775 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
778 /* skip leading "URL:" (if any) */
779 if ( strnequal( uri, "URL:", 4 ) ) {
780 uri += 4;
783 sscanf(uri, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
785 if (port == 0) {
786 if (strequal(protocol, "ldap")) {
787 port = LDAP_PORT;
788 } else if (strequal(protocol, "ldaps")) {
789 port = LDAPS_PORT;
790 } else {
791 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
795 if ((*ldap_struct = ldap_init(host, port)) == NULL) {
796 DEBUG(0, ("ldap_init failed !\n"));
797 return LDAP_OPERATIONS_ERROR;
800 if (strequal(protocol, "ldaps")) {
801 #ifdef LDAP_OPT_X_TLS
802 int tls = LDAP_OPT_X_TLS_HARD;
803 if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
805 DEBUG(0, ("Failed to setup a TLS session\n"));
808 DEBUG(3,("LDAPS option set...!\n"));
809 #else
810 DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
811 return LDAP_OPERATIONS_ERROR;
812 #endif /* LDAP_OPT_X_TLS */
815 #endif /* HAVE_LDAP_INITIALIZE */
817 /* now set connection timeout */
818 #ifdef LDAP_X_OPT_CONNECT_TIMEOUT /* Netscape */
820 int ct = lp_ldap_connection_timeout()*1000;
821 rc = ldap_set_option(*ldap_struct, LDAP_X_OPT_CONNECT_TIMEOUT, &ct);
822 if (rc != LDAP_SUCCESS) {
823 DEBUG(0,("Failed to setup an ldap connection timeout %d: %s\n",
824 ct, ldap_err2string(rc)));
827 #elif defined (LDAP_OPT_NETWORK_TIMEOUT) /* OpenLDAP */
829 struct timeval ct;
830 ct.tv_usec = 0;
831 ct.tv_sec = lp_ldap_connection_timeout();
832 rc = ldap_set_option(*ldap_struct, LDAP_OPT_NETWORK_TIMEOUT, &ct);
833 if (rc != LDAP_SUCCESS) {
834 DEBUG(0,("Failed to setup an ldap connection timeout %d: %s\n",
835 (int)ct.tv_sec, ldap_err2string(rc)));
838 #endif
840 return LDAP_SUCCESS;
843 /********************************************************************
844 try to upgrade to Version 3 LDAP if not already, in either case return current
845 version
846 *******************************************************************/
848 static int smb_ldap_upgrade_conn(LDAP *ldap_struct, int *new_version)
850 int version;
851 int rc;
853 /* assume the worst */
854 *new_version = LDAP_VERSION2;
856 rc = ldap_get_option(ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
857 if (rc) {
858 return rc;
861 if (version == LDAP_VERSION3) {
862 *new_version = LDAP_VERSION3;
863 return LDAP_SUCCESS;
866 /* try upgrade */
867 version = LDAP_VERSION3;
868 rc = ldap_set_option (ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
869 if (rc) {
870 return rc;
873 *new_version = LDAP_VERSION3;
874 return LDAP_SUCCESS;
877 /*******************************************************************
878 open a connection to the ldap server (just until the bind)
879 ******************************************************************/
881 int smb_ldap_setup_full_conn(LDAP **ldap_struct, const char *uri)
883 int rc, version;
885 rc = smb_ldap_setup_conn(ldap_struct, uri);
886 if (rc) {
887 return rc;
890 rc = smb_ldap_upgrade_conn(*ldap_struct, &version);
891 if (rc) {
892 return rc;
895 rc = smb_ldap_start_tls(*ldap_struct, version);
896 if (rc) {
897 return rc;
900 return LDAP_SUCCESS;
903 /*******************************************************************
904 open a connection to the ldap server.
905 ******************************************************************/
906 static int smbldap_open_connection (struct smbldap_state *ldap_state)
909 int rc = LDAP_SUCCESS;
910 int version;
911 int deref;
912 LDAP **ldap_struct = &ldap_state->ldap_struct;
914 rc = smb_ldap_setup_conn(ldap_struct, ldap_state->uri);
915 if (rc) {
916 return rc;
919 /* Store the LDAP pointer in a lookup list */
921 smbldap_store_state(*ldap_struct, ldap_state);
923 /* Upgrade to LDAPv3 if possible */
925 rc = smb_ldap_upgrade_conn(*ldap_struct, &version);
926 if (rc) {
927 return rc;
930 /* Start TLS if required */
932 rc = smb_ldap_start_tls(*ldap_struct, version);
933 if (rc) {
934 return rc;
937 /* Set alias dereferencing method */
938 deref = lp_ldap_deref();
939 if (deref != -1) {
940 if (ldap_set_option (*ldap_struct, LDAP_OPT_DEREF, &deref) != LDAP_OPT_SUCCESS) {
941 DEBUG(1,("smbldap_open_connection: Failed to set dereferencing method: %d\n", deref));
942 } else {
943 DEBUG(5,("Set dereferencing method: %d\n", deref));
947 DEBUG(2, ("smbldap_open_connection: connection opened\n"));
948 return rc;
951 /*******************************************************************
952 a rebind function for authenticated referrals
953 This version takes a void* that we can shove useful stuff in :-)
954 ******************************************************************/
955 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
956 #else
957 static int rebindproc_with_state (LDAP * ld, char **whop, char **credp,
958 int *methodp, int freeit, void *arg)
960 struct smbldap_state *ldap_state = arg;
961 struct timespec ts;
963 /** @TODO Should we be doing something to check what servers we rebind to?
964 Could we get a referral to a machine that we don't want to give our
965 username and password to? */
967 if (freeit) {
968 SAFE_FREE(*whop);
969 if (*credp) {
970 memset(*credp, '\0', strlen(*credp));
972 SAFE_FREE(*credp);
973 } else {
974 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n",
975 ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
977 if (ldap_state->anonymous) {
978 *whop = NULL;
979 *credp = NULL;
980 } else {
981 *whop = SMB_STRDUP(ldap_state->bind_dn);
982 if (!*whop) {
983 return LDAP_NO_MEMORY;
985 *credp = SMB_STRDUP(ldap_state->bind_secret);
986 if (!*credp) {
987 SAFE_FREE(*whop);
988 return LDAP_NO_MEMORY;
991 *methodp = LDAP_AUTH_SIMPLE;
994 clock_gettime_mono(&ts);
995 ldap_state->last_rebind = convert_timespec_to_timeval(ts);
997 return 0;
999 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1001 /*******************************************************************
1002 a rebind function for authenticated referrals
1003 This version takes a void* that we can shove useful stuff in :-)
1004 and actually does the connection.
1005 ******************************************************************/
1006 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1007 static int rebindproc_connect_with_state (LDAP *ldap_struct,
1008 LDAP_CONST char *url,
1009 ber_tag_t request,
1010 ber_int_t msgid, void *arg)
1012 struct smbldap_state *ldap_state =
1013 (struct smbldap_state *)arg;
1014 int rc;
1015 struct timespec ts;
1016 int version;
1018 DEBUG(5,("rebindproc_connect_with_state: Rebinding to %s as \"%s\"\n",
1019 url, ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
1021 /* call START_TLS again (ldaps:// is handled by the OpenLDAP library
1022 * itself) before rebinding to another LDAP server to avoid to expose
1023 * our credentials. At least *try* to secure the connection - Guenther */
1025 smb_ldap_upgrade_conn(ldap_struct, &version);
1026 smb_ldap_start_tls(ldap_struct, version);
1028 /** @TODO Should we be doing something to check what servers we rebind to?
1029 Could we get a referral to a machine that we don't want to give our
1030 username and password to? */
1032 rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
1034 /* only set the last rebind timestamp when we did rebind after a
1035 * non-read LDAP operation. That way we avoid the replication sleep
1036 * after a simple redirected search operation - Guenther */
1038 switch (request) {
1040 case LDAP_REQ_MODIFY:
1041 case LDAP_REQ_ADD:
1042 case LDAP_REQ_DELETE:
1043 case LDAP_REQ_MODDN:
1044 case LDAP_REQ_EXTENDED:
1045 DEBUG(10,("rebindproc_connect_with_state: "
1046 "setting last_rebind timestamp "
1047 "(req: 0x%02x)\n", (unsigned int)request));
1048 clock_gettime_mono(&ts);
1049 ldap_state->last_rebind = convert_timespec_to_timeval(ts);
1050 break;
1051 default:
1052 ZERO_STRUCT(ldap_state->last_rebind);
1053 break;
1056 return rc;
1058 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1060 /*******************************************************************
1061 Add a rebind function for authenticated referrals
1062 ******************************************************************/
1063 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1064 #else
1065 # if LDAP_SET_REBIND_PROC_ARGS == 2
1066 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
1067 int *method, int freeit )
1069 struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
1071 return rebindproc_with_state(ldap_struct, whop, credp,
1072 method, freeit, ldap_state);
1074 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
1075 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1077 /*******************************************************************
1078 a rebind function for authenticated referrals
1079 this also does the connection, but no void*.
1080 ******************************************************************/
1081 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1082 # if LDAP_SET_REBIND_PROC_ARGS == 2
1083 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
1084 ber_int_t msgid)
1086 struct smbldap_state *ldap_state = smbldap_find_state(ld);
1088 return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid,
1089 ldap_state);
1091 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
1092 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1094 /*******************************************************************
1095 connect to the ldap server under system privilege.
1096 ******************************************************************/
1097 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
1099 int rc;
1100 int version;
1102 if (!ldap_state->anonymous && !ldap_state->bind_dn) {
1103 char *bind_dn = NULL;
1104 char *bind_secret = NULL;
1106 /* get the default dn and password only if they are not set already */
1107 if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
1108 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
1109 return LDAP_INVALID_CREDENTIALS;
1111 smbldap_set_creds(ldap_state, false, bind_dn, bind_secret);
1112 SAFE_FREE(bind_dn);
1113 memset(bind_secret, '\0', strlen(bind_secret));
1114 SAFE_FREE(bind_secret);
1117 /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite
1118 (OpenLDAP) doesnt' seem to support it */
1120 DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
1121 ldap_state->uri, ldap_state->bind_dn));
1123 #ifdef HAVE_LDAP_SET_REBIND_PROC
1124 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1125 # if LDAP_SET_REBIND_PROC_ARGS == 2
1126 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect);
1127 # endif
1128 # if LDAP_SET_REBIND_PROC_ARGS == 3
1129 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);
1130 # endif
1131 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1132 # if LDAP_SET_REBIND_PROC_ARGS == 2
1133 ldap_set_rebind_proc(ldap_struct, &rebindproc);
1134 # endif
1135 # if LDAP_SET_REBIND_PROC_ARGS == 3
1136 ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);
1137 # endif
1138 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1139 #endif
1141 rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
1143 if (rc != LDAP_SUCCESS) {
1144 char *ld_error = NULL;
1145 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1146 &ld_error);
1147 DEBUG(ldap_state->num_failures ? 2 : 0,
1148 ("failed to bind to server %s with dn=\"%s\" Error: %s\n\t%s\n",
1149 ldap_state->uri,
1150 ldap_state->bind_dn ? ldap_state->bind_dn : "[Anonymous bind]",
1151 ldap_err2string(rc),
1152 ld_error ? ld_error : "(unknown)"));
1153 SAFE_FREE(ld_error);
1154 ldap_state->num_failures++;
1155 return rc;
1158 ldap_state->num_failures = 0;
1159 ldap_state->paged_results = False;
1161 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
1163 if (smbldap_has_control(ldap_state->ldap_struct, ADS_PAGE_CTL_OID) && version == 3) {
1164 ldap_state->paged_results = True;
1167 DEBUG(3, ("ldap_connect_system: successful connection to the LDAP server\n"));
1168 DEBUGADD(10, ("ldap_connect_system: LDAP server %s support paged results\n",
1169 ldap_state->paged_results ? "does" : "does not"));
1170 return rc;
1173 static void smbldap_idle_fn(struct event_context *event_ctx,
1174 struct timed_event *te,
1175 struct timeval now_abs,
1176 void *private_data);
1178 /**********************************************************************
1179 Connect to LDAP server (called before every ldap operation)
1180 *********************************************************************/
1181 static int smbldap_open(struct smbldap_state *ldap_state)
1183 int rc, opt_rc;
1184 bool reopen = False;
1185 SMB_ASSERT(ldap_state);
1187 if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time_mono(NULL))) {
1189 #ifdef HAVE_UNIXSOCKET
1190 struct sockaddr_un addr;
1191 #else
1192 struct sockaddr addr;
1193 #endif
1194 socklen_t len = sizeof(addr);
1195 int sd;
1197 opt_rc = ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd);
1198 if (opt_rc == 0 && (getpeername(sd, (struct sockaddr *) &addr, &len)) < 0 )
1199 reopen = True;
1201 #ifdef HAVE_UNIXSOCKET
1202 if (opt_rc == 0 && addr.sun_family == AF_UNIX)
1203 reopen = True;
1204 #endif
1205 if (reopen) {
1206 /* the other end has died. reopen. */
1207 ldap_unbind(ldap_state->ldap_struct);
1208 ldap_state->ldap_struct = NULL;
1209 ldap_state->last_ping = (time_t)0;
1210 } else {
1211 ldap_state->last_ping = time_mono(NULL);
1215 if (ldap_state->ldap_struct != NULL) {
1216 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
1217 return LDAP_SUCCESS;
1220 if ((rc = smbldap_open_connection(ldap_state))) {
1221 return rc;
1224 if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
1225 ldap_unbind(ldap_state->ldap_struct);
1226 ldap_state->ldap_struct = NULL;
1227 return rc;
1231 ldap_state->last_ping = time_mono(NULL);
1232 ldap_state->pid = sys_getpid();
1234 TALLOC_FREE(ldap_state->idle_event);
1236 if (ldap_state->event_context != NULL) {
1237 ldap_state->idle_event = event_add_timed(
1238 ldap_state->event_context, NULL,
1239 timeval_current_ofs(SMBLDAP_IDLE_TIME, 0),
1240 smbldap_idle_fn, ldap_state);
1243 DEBUG(4,("The LDAP server is successfully connected\n"));
1245 return LDAP_SUCCESS;
1248 /**********************************************************************
1249 Disconnect from LDAP server
1250 *********************************************************************/
1251 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
1253 if (!ldap_state)
1254 return NT_STATUS_INVALID_PARAMETER;
1256 if (ldap_state->ldap_struct != NULL) {
1257 ldap_unbind(ldap_state->ldap_struct);
1258 ldap_state->ldap_struct = NULL;
1261 smbldap_delete_state(ldap_state);
1263 DEBUG(5,("The connection to the LDAP server was closed\n"));
1264 /* maybe free the results here --metze */
1266 return NT_STATUS_OK;
1269 static bool got_alarm;
1271 static void (*old_handler)(int);
1273 static void gotalarm_sig(int dummy)
1275 got_alarm = True;
1278 static int another_ldap_try(struct smbldap_state *ldap_state, int *rc,
1279 int *attempts, time_t endtime)
1281 time_t now = time_mono(NULL);
1282 int open_rc = LDAP_SERVER_DOWN;
1284 if (*rc != LDAP_SERVER_DOWN)
1285 goto no_next;
1287 if (now >= endtime) {
1288 smbldap_close(ldap_state);
1289 *rc = LDAP_TIMEOUT;
1290 goto no_next;
1293 if (*attempts == 0) {
1294 got_alarm = False;
1295 old_handler = CatchSignal(SIGALRM, gotalarm_sig);
1296 alarm(endtime - now);
1298 if (ldap_state->pid != sys_getpid())
1299 smbldap_close(ldap_state);
1302 while (1) {
1304 if (*attempts != 0)
1305 smb_msleep(1000);
1307 *attempts += 1;
1309 open_rc = smbldap_open(ldap_state);
1311 if (open_rc == LDAP_SUCCESS) {
1312 ldap_state->last_use = now;
1313 return True;
1316 if (open_rc == LDAP_INSUFFICIENT_ACCESS) {
1317 /* The fact that we are non-root or any other
1318 * access-denied condition will not change in the next
1319 * round of trying */
1320 *rc = open_rc;
1321 break;
1324 if (got_alarm) {
1325 *rc = LDAP_TIMEOUT;
1326 break;
1329 if (open_rc != LDAP_SUCCESS) {
1330 DEBUG(1, ("Connection to LDAP server failed for the "
1331 "%d try!\n", *attempts));
1335 no_next:
1336 CatchSignal(SIGALRM, old_handler);
1337 alarm(0);
1338 ldap_state->last_use = now;
1339 return False;
1342 /*********************************************************************
1343 ********************************************************************/
1345 static int smbldap_search_ext(struct smbldap_state *ldap_state,
1346 const char *base, int scope, const char *filter,
1347 const char *attrs[], int attrsonly,
1348 LDAPControl **sctrls, LDAPControl **cctrls,
1349 int sizelimit, LDAPMessage **res)
1351 int rc = LDAP_SERVER_DOWN;
1352 int attempts = 0;
1353 char *utf8_filter;
1354 time_t endtime = time_mono(NULL)+lp_ldap_timeout();
1355 struct timeval timeout;
1356 size_t converted_size;
1358 SMB_ASSERT(ldap_state);
1360 DEBUG(5,("smbldap_search_ext: base => [%s], filter => [%s], "
1361 "scope => [%d]\n", base, filter, scope));
1363 if (ldap_state->last_rebind.tv_sec > 0) {
1364 struct timeval tval;
1365 struct timespec ts;
1366 int64_t tdiff = 0;
1367 int sleep_time = 0;
1369 clock_gettime_mono(&ts);
1370 tval = convert_timespec_to_timeval(ts);
1372 tdiff = usec_time_diff(&tval, &ldap_state->last_rebind);
1373 tdiff /= 1000; /* Convert to milliseconds. */
1375 sleep_time = lp_ldap_replication_sleep()-(int)tdiff;
1376 sleep_time = MIN(sleep_time, MAX_LDAP_REPLICATION_SLEEP_TIME);
1378 if (sleep_time > 0) {
1379 /* we wait for the LDAP replication */
1380 DEBUG(5,("smbldap_search_ext: waiting %d milliseconds "
1381 "for LDAP replication.\n",sleep_time));
1382 smb_msleep(sleep_time);
1383 DEBUG(5,("smbldap_search_ext: go on!\n"));
1385 ZERO_STRUCT(ldap_state->last_rebind);
1388 if (!push_utf8_talloc(talloc_tos(), &utf8_filter, filter, &converted_size)) {
1389 return LDAP_NO_MEMORY;
1392 /* Setup timeout for the ldap_search_ext_s call - local and remote. */
1393 timeout.tv_sec = lp_ldap_timeout();
1394 timeout.tv_usec = 0;
1396 /* Setup alarm timeout.... Do we need both of these ? JRA.
1397 * Yes, I think we do need both of these. The server timeout only
1398 * covers the case where the server's operation takes too long. It
1399 * does not cover the case where the request hangs on its way to the
1400 * server. The server side timeout is not strictly necessary, it's
1401 * just a bit more kind to the server. VL. */
1403 got_alarm = 0;
1404 CatchSignal(SIGALRM, gotalarm_sig);
1405 alarm(lp_ldap_timeout());
1406 /* End setup timeout. */
1408 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1409 rc = ldap_search_ext_s(ldap_state->ldap_struct, base, scope,
1410 utf8_filter,
1411 CONST_DISCARD(char **, attrs),
1412 attrsonly, sctrls, cctrls, &timeout,
1413 sizelimit, res);
1414 if (rc != LDAP_SUCCESS) {
1415 char *ld_error = NULL;
1416 int ld_errno;
1418 ldap_get_option(ldap_state->ldap_struct,
1419 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1421 ldap_get_option(ldap_state->ldap_struct,
1422 LDAP_OPT_ERROR_STRING, &ld_error);
1423 DEBUG(10, ("Failed search for base: %s, error: %d (%s) "
1424 "(%s)\n", base, ld_errno,
1425 ldap_err2string(rc),
1426 ld_error ? ld_error : "unknown"));
1427 SAFE_FREE(ld_error);
1429 if (ld_errno == LDAP_SERVER_DOWN) {
1430 ldap_unbind(ldap_state->ldap_struct);
1431 ldap_state->ldap_struct = NULL;
1436 TALLOC_FREE(utf8_filter);
1438 /* Teardown timeout. */
1439 CatchSignal(SIGALRM, SIG_IGN);
1440 alarm(0);
1442 if (got_alarm != 0)
1443 return LDAP_TIMELIMIT_EXCEEDED;
1445 return rc;
1448 int smbldap_search(struct smbldap_state *ldap_state,
1449 const char *base, int scope, const char *filter,
1450 const char *attrs[], int attrsonly,
1451 LDAPMessage **res)
1453 return smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1454 attrsonly, NULL, NULL, LDAP_NO_LIMIT, res);
1457 int smbldap_search_paged(struct smbldap_state *ldap_state,
1458 const char *base, int scope, const char *filter,
1459 const char **attrs, int attrsonly, int pagesize,
1460 LDAPMessage **res, void **cookie)
1462 LDAPControl pr;
1463 LDAPControl **rcontrols;
1464 LDAPControl *controls[2] = { NULL, NULL};
1465 BerElement *cookie_be = NULL;
1466 struct berval *cookie_bv = NULL;
1467 int tmp = 0, i, rc;
1468 bool critical = True;
1470 *res = NULL;
1472 DEBUG(3,("smbldap_search_paged: base => [%s], filter => [%s],"
1473 "scope => [%d], pagesize => [%d]\n",
1474 base, filter, scope, pagesize));
1476 cookie_be = ber_alloc_t(LBER_USE_DER);
1477 if (cookie_be == NULL) {
1478 DEBUG(0,("smbldap_create_page_control: ber_alloc_t returns "
1479 "NULL\n"));
1480 return LDAP_NO_MEMORY;
1483 /* construct cookie */
1484 if (*cookie != NULL) {
1485 ber_printf(cookie_be, "{iO}", (ber_int_t) pagesize, *cookie);
1486 ber_bvfree((struct berval *)*cookie); /* don't need it from last time */
1487 *cookie = NULL;
1488 } else {
1489 ber_printf(cookie_be, "{io}", (ber_int_t) pagesize, "", 0);
1491 ber_flatten(cookie_be, &cookie_bv);
1493 pr.ldctl_oid = CONST_DISCARD(char *, ADS_PAGE_CTL_OID);
1494 pr.ldctl_iscritical = (char) critical;
1495 pr.ldctl_value.bv_len = cookie_bv->bv_len;
1496 pr.ldctl_value.bv_val = cookie_bv->bv_val;
1498 controls[0] = &pr;
1499 controls[1] = NULL;
1501 rc = smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1502 0, controls, NULL, LDAP_NO_LIMIT, res);
1504 ber_free(cookie_be, 1);
1505 ber_bvfree(cookie_bv);
1507 if (rc != 0) {
1508 DEBUG(3,("smbldap_search_paged: smbldap_search_ext(%s) "
1509 "failed with [%s]\n", filter, ldap_err2string(rc)));
1510 goto done;
1513 DEBUG(3,("smbldap_search_paged: search was successful\n"));
1515 rc = ldap_parse_result(ldap_state->ldap_struct, *res, NULL, NULL,
1516 NULL, NULL, &rcontrols, 0);
1517 if (rc != 0) {
1518 DEBUG(3,("smbldap_search_paged: ldap_parse_result failed " \
1519 "with [%s]\n", ldap_err2string(rc)));
1520 goto done;
1523 if (rcontrols == NULL)
1524 goto done;
1526 for (i=0; rcontrols[i]; i++) {
1528 if (strcmp(ADS_PAGE_CTL_OID, rcontrols[i]->ldctl_oid) != 0)
1529 continue;
1531 cookie_be = ber_init(&rcontrols[i]->ldctl_value);
1532 ber_scanf(cookie_be,"{iO}", &tmp, &cookie_bv);
1533 /* the berval is the cookie, but must be freed when it is all
1534 done */
1535 if (cookie_bv->bv_len)
1536 *cookie=ber_bvdup(cookie_bv);
1537 else
1538 *cookie=NULL;
1539 ber_bvfree(cookie_bv);
1540 ber_free(cookie_be, 1);
1541 break;
1543 ldap_controls_free(rcontrols);
1544 done:
1545 return rc;
1548 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1550 int rc = LDAP_SERVER_DOWN;
1551 int attempts = 0;
1552 char *utf8_dn;
1553 time_t endtime = time_mono(NULL)+lp_ldap_timeout();;
1554 size_t converted_size;
1556 SMB_ASSERT(ldap_state);
1558 DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1560 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1561 return LDAP_NO_MEMORY;
1564 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1565 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1566 if (rc != LDAP_SUCCESS) {
1567 char *ld_error = NULL;
1568 int ld_errno;
1570 ldap_get_option(ldap_state->ldap_struct,
1571 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1573 ldap_get_option(ldap_state->ldap_struct,
1574 LDAP_OPT_ERROR_STRING, &ld_error);
1575 DEBUG(10, ("Failed to modify dn: %s, error: %d (%s) "
1576 "(%s)\n", dn, ld_errno,
1577 ldap_err2string(rc),
1578 ld_error ? ld_error : "unknown"));
1579 SAFE_FREE(ld_error);
1581 if (ld_errno == LDAP_SERVER_DOWN) {
1582 ldap_unbind(ldap_state->ldap_struct);
1583 ldap_state->ldap_struct = NULL;
1588 TALLOC_FREE(utf8_dn);
1589 return rc;
1592 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1594 int rc = LDAP_SERVER_DOWN;
1595 int attempts = 0;
1596 char *utf8_dn;
1597 time_t endtime = time_mono(NULL)+lp_ldap_timeout();;
1598 size_t converted_size;
1600 SMB_ASSERT(ldap_state);
1602 DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1604 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1605 return LDAP_NO_MEMORY;
1608 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1609 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1610 if (rc != LDAP_SUCCESS) {
1611 char *ld_error = NULL;
1612 int ld_errno;
1614 ldap_get_option(ldap_state->ldap_struct,
1615 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1617 ldap_get_option(ldap_state->ldap_struct,
1618 LDAP_OPT_ERROR_STRING, &ld_error);
1619 DEBUG(10, ("Failed to add dn: %s, error: %d (%s) "
1620 "(%s)\n", dn, ld_errno,
1621 ldap_err2string(rc),
1622 ld_error ? ld_error : "unknown"));
1623 SAFE_FREE(ld_error);
1625 if (ld_errno == LDAP_SERVER_DOWN) {
1626 ldap_unbind(ldap_state->ldap_struct);
1627 ldap_state->ldap_struct = NULL;
1632 TALLOC_FREE(utf8_dn);
1633 return rc;
1636 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1638 int rc = LDAP_SERVER_DOWN;
1639 int attempts = 0;
1640 char *utf8_dn;
1641 time_t endtime = time_mono(NULL)+lp_ldap_timeout();;
1642 size_t converted_size;
1644 SMB_ASSERT(ldap_state);
1646 DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1648 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1649 return LDAP_NO_MEMORY;
1652 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1653 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1654 if (rc != LDAP_SUCCESS) {
1655 char *ld_error = NULL;
1656 int ld_errno;
1658 ldap_get_option(ldap_state->ldap_struct,
1659 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1661 ldap_get_option(ldap_state->ldap_struct,
1662 LDAP_OPT_ERROR_STRING, &ld_error);
1663 DEBUG(10, ("Failed to delete dn: %s, error: %d (%s) "
1664 "(%s)\n", dn, ld_errno,
1665 ldap_err2string(rc),
1666 ld_error ? ld_error : "unknown"));
1667 SAFE_FREE(ld_error);
1669 if (ld_errno == LDAP_SERVER_DOWN) {
1670 ldap_unbind(ldap_state->ldap_struct);
1671 ldap_state->ldap_struct = NULL;
1676 TALLOC_FREE(utf8_dn);
1677 return rc;
1680 int smbldap_extended_operation(struct smbldap_state *ldap_state,
1681 LDAP_CONST char *reqoid, struct berval *reqdata,
1682 LDAPControl **serverctrls, LDAPControl **clientctrls,
1683 char **retoidp, struct berval **retdatap)
1685 int rc = LDAP_SERVER_DOWN;
1686 int attempts = 0;
1687 time_t endtime = time_mono(NULL)+lp_ldap_timeout();
1689 if (!ldap_state)
1690 return (-1);
1692 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1693 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid,
1694 reqdata, serverctrls,
1695 clientctrls, retoidp, retdatap);
1696 if (rc != LDAP_SUCCESS) {
1697 char *ld_error = NULL;
1698 int ld_errno;
1700 ldap_get_option(ldap_state->ldap_struct,
1701 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1703 ldap_get_option(ldap_state->ldap_struct,
1704 LDAP_OPT_ERROR_STRING, &ld_error);
1705 DEBUG(10, ("Extended operation failed with error: "
1706 "%d (%s) (%s)\n", ld_errno,
1707 ldap_err2string(rc),
1708 ld_error ? ld_error : "unknown"));
1709 SAFE_FREE(ld_error);
1711 if (ld_errno == LDAP_SERVER_DOWN) {
1712 ldap_unbind(ldap_state->ldap_struct);
1713 ldap_state->ldap_struct = NULL;
1718 return rc;
1721 /*******************************************************************
1722 run the search by name.
1723 ******************************************************************/
1724 int smbldap_search_suffix (struct smbldap_state *ldap_state,
1725 const char *filter, const char **search_attr,
1726 LDAPMessage ** result)
1728 return smbldap_search(ldap_state, lp_ldap_suffix(), LDAP_SCOPE_SUBTREE,
1729 filter, search_attr, 0, result);
1732 static void smbldap_idle_fn(struct event_context *event_ctx,
1733 struct timed_event *te,
1734 struct timeval now_abs,
1735 void *private_data)
1737 struct smbldap_state *state = (struct smbldap_state *)private_data;
1739 TALLOC_FREE(state->idle_event);
1741 if (state->ldap_struct == NULL) {
1742 DEBUG(10,("ldap connection not connected...\n"));
1743 return;
1746 if ((state->last_use+SMBLDAP_IDLE_TIME) > time_mono(NULL)) {
1747 DEBUG(10,("ldap connection not idle...\n"));
1749 /* this needs to be made monotonic clock aware inside tevent: */
1750 state->idle_event = event_add_timed(
1751 event_ctx, NULL,
1752 timeval_add(&now_abs, SMBLDAP_IDLE_TIME, 0),
1753 smbldap_idle_fn,
1754 private_data);
1755 return;
1758 DEBUG(7,("ldap connection idle...closing connection\n"));
1759 smbldap_close(state);
1762 /**********************************************************************
1763 Housekeeping
1764 *********************************************************************/
1766 void smbldap_free_struct(struct smbldap_state **ldap_state)
1768 smbldap_close(*ldap_state);
1770 if ((*ldap_state)->bind_secret) {
1771 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1774 SAFE_FREE((*ldap_state)->bind_dn);
1775 SAFE_FREE((*ldap_state)->bind_secret);
1777 TALLOC_FREE((*ldap_state)->idle_event);
1779 *ldap_state = NULL;
1781 /* No need to free any further, as it is talloc()ed */
1785 /**********************************************************************
1786 Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1787 *********************************************************************/
1789 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, struct event_context *event_ctx,
1790 const char *location,
1791 struct smbldap_state **smbldap_state)
1793 *smbldap_state = TALLOC_ZERO_P(mem_ctx, struct smbldap_state);
1794 if (!*smbldap_state) {
1795 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1796 return NT_STATUS_NO_MEMORY;
1799 if (location) {
1800 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1801 } else {
1802 (*smbldap_state)->uri = "ldap://localhost";
1805 (*smbldap_state)->event_context = event_ctx;
1807 return NT_STATUS_OK;
1810 char *smbldap_talloc_dn(TALLOC_CTX *mem_ctx, LDAP *ld,
1811 LDAPMessage *entry)
1813 char *utf8_dn, *unix_dn;
1814 size_t converted_size;
1816 utf8_dn = ldap_get_dn(ld, entry);
1817 if (!utf8_dn) {
1818 DEBUG (5, ("smbldap_talloc_dn: ldap_get_dn failed\n"));
1819 return NULL;
1821 if (!pull_utf8_talloc(mem_ctx, &unix_dn, utf8_dn, &converted_size)) {
1822 DEBUG (0, ("smbldap_talloc_dn: String conversion failure utf8 "
1823 "[%s]\n", utf8_dn));
1824 return NULL;
1826 ldap_memfree(utf8_dn);
1827 return unix_dn;
1830 /*******************************************************************
1831 Check if root-dse has a certain Control or Extension
1832 ********************************************************************/
1834 static bool smbldap_check_root_dse(LDAP *ld, const char **attrs, const char *value)
1836 LDAPMessage *msg = NULL;
1837 LDAPMessage *entry = NULL;
1838 char **values = NULL;
1839 int rc, num_result, num_values, i;
1840 bool result = False;
1842 if (!attrs[0]) {
1843 DEBUG(3,("smbldap_check_root_dse: nothing to look for\n"));
1844 return False;
1847 if (!strequal(attrs[0], "supportedExtension") &&
1848 !strequal(attrs[0], "supportedControl") &&
1849 !strequal(attrs[0], "namingContexts")) {
1850 DEBUG(3,("smbldap_check_root_dse: no idea what to query root-dse for: %s ?\n", attrs[0]));
1851 return False;
1854 rc = ldap_search_s(ld, "", LDAP_SCOPE_BASE,
1855 "(objectclass=*)", CONST_DISCARD(char **, attrs), 0 , &msg);
1857 if (rc != LDAP_SUCCESS) {
1858 DEBUG(3,("smbldap_check_root_dse: Could not search rootDSE\n"));
1859 return False;
1862 num_result = ldap_count_entries(ld, msg);
1864 if (num_result != 1) {
1865 DEBUG(3,("smbldap_check_root_dse: Expected one rootDSE, got %d\n", num_result));
1866 goto done;
1869 entry = ldap_first_entry(ld, msg);
1871 if (entry == NULL) {
1872 DEBUG(3,("smbldap_check_root_dse: Could not retrieve rootDSE\n"));
1873 goto done;
1876 values = ldap_get_values(ld, entry, attrs[0]);
1878 if (values == NULL) {
1879 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not support any %s\n", attrs[0]));
1880 goto done;
1883 num_values = ldap_count_values(values);
1885 if (num_values == 0) {
1886 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not have any %s\n", attrs[0]));
1887 goto done;
1890 for (i=0; i<num_values; i++) {
1891 if (strcmp(values[i], value) == 0)
1892 result = True;
1896 done:
1897 if (values != NULL)
1898 ldap_value_free(values);
1899 if (msg != NULL)
1900 ldap_msgfree(msg);
1902 return result;
1906 /*******************************************************************
1907 Check if LDAP-Server supports a certain Control (OID in string format)
1908 ********************************************************************/
1910 bool smbldap_has_control(LDAP *ld, const char *control)
1912 const char *attrs[] = { "supportedControl", NULL };
1913 return smbldap_check_root_dse(ld, attrs, control);
1916 /*******************************************************************
1917 Check if LDAP-Server supports a certain Extension (OID in string format)
1918 ********************************************************************/
1920 bool smbldap_has_extension(LDAP *ld, const char *extension)
1922 const char *attrs[] = { "supportedExtension", NULL };
1923 return smbldap_check_root_dse(ld, attrs, extension);
1926 /*******************************************************************
1927 Check if LDAP-Server holds a given namingContext
1928 ********************************************************************/
1930 bool smbldap_has_naming_context(LDAP *ld, const char *naming_context)
1932 const char *attrs[] = { "namingContexts", NULL };
1933 return smbldap_check_root_dse(ld, attrs, naming_context);
1936 bool smbldap_set_creds(struct smbldap_state *ldap_state, bool anon, const char *dn, const char *secret)
1938 ldap_state->anonymous = anon;
1940 /* free any previously set credential */
1942 SAFE_FREE(ldap_state->bind_dn);
1943 if (ldap_state->bind_secret) {
1944 /* make sure secrets are zeroed out of memory */
1945 memset(ldap_state->bind_secret, '\0', strlen(ldap_state->bind_secret));
1946 SAFE_FREE(ldap_state->bind_secret);
1949 if ( ! anon) {
1950 ldap_state->bind_dn = SMB_STRDUP(dn);
1951 ldap_state->bind_secret = SMB_STRDUP(secret);
1954 return True;