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/>.
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 )
218 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
219 if ( table[i].attrib == key )
220 return table[i].name;
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[] )
237 while ( table[i].attrib != LDAP_ATTR_LIST_END )
241 names = TALLOC_ARRAY( mem_ctx, const char*, i );
243 DEBUG(0,("get_attr_list: out of memory\n"));
248 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
249 names[i] = talloc_strdup( names, table[i].name );
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,
272 if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
273 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
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);
285 ldap_value_free(values);
286 #ifdef DEBUG_PASSWORDS
287 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
292 char * smbldap_talloc_single_attribute(LDAP *ldap_struct, LDAPMessage *entry,
293 const char *attribute,
298 size_t converted_size;
300 if (attribute == NULL) {
304 values = ldap_get_values(ldap_struct, entry, attribute);
306 if (values == NULL) {
307 DEBUG(10, ("attribute %s does not exist\n", attribute));
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);
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);
324 ldap_value_free(values);
326 #ifdef DEBUG_PASSWORDS
327 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n",
333 char * smbldap_talloc_first_attribute(LDAP *ldap_struct, LDAPMessage *entry,
334 const char *attribute,
339 size_t converted_size;
341 if (attribute == NULL) {
345 values = ldap_get_values(ldap_struct, entry, attribute);
347 if (values == NULL) {
348 DEBUG(10, ("attribute %s does not exist\n", attribute));
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);
358 ldap_value_free(values);
360 #ifdef DEBUG_PASSWORDS
361 DEBUG (100, ("smbldap_get_first_attribute: [%s] = [%s]\n",
367 char * smbldap_talloc_smallest_attribute(LDAP *ldap_struct, LDAPMessage *entry,
368 const char *attribute,
373 size_t converted_size;
376 if (attribute == NULL) {
380 values = ldap_get_values(ldap_struct, entry, attribute);
382 if (values == NULL) {
383 DEBUG(10, ("attribute %s does not exist\n", attribute));
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);
393 num_values = ldap_count_values(values);
395 for (i=1; i<num_values; i++) {
398 if (!pull_utf8_talloc(mem_ctx, &tmp, values[i],
400 DEBUG(10, ("pull_utf8_talloc failed\n"));
402 ldap_value_free(values);
406 if (StrCaseCmp(tmp, result) < 0) {
414 ldap_value_free(values);
416 #ifdef DEBUG_PASSWORDS
417 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n",
423 bool smbldap_talloc_single_blob(TALLOC_CTX *mem_ctx, LDAP *ld,
424 LDAPMessage *msg, const char *attrib,
427 struct berval **values;
429 values = ldap_get_values_len(ld, msg, attrib);
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)));
440 *blob = data_blob_talloc(mem_ctx, values[0]->bv_val,
442 ldap_value_free_len(values);
444 return (blob->data != NULL);
447 bool smbldap_pull_sid(LDAP *ld, LDAPMessage *msg, const char *attrib,
453 if (!smbldap_talloc_single_blob(talloc_tos(), ld, msg, attrib,
457 ret = sid_parse((char *)blob.data, blob.length, sid);
458 TALLOC_FREE(blob.data);
462 static int ldapmsg_destructor(LDAPMessage **result) {
463 ldap_msgfree(*result);
467 void talloc_autofree_ldapmsg(TALLOC_CTX *mem_ctx, LDAPMessage *result)
469 LDAPMessage **handle;
471 if (result == NULL) {
475 handle = TALLOC_P(mem_ctx, LDAPMessage *);
476 SMB_ASSERT(handle != NULL);
479 talloc_set_destructor(handle, ldapmsg_destructor);
482 static int ldapmod_destructor(LDAPMod ***mod) {
483 ldap_mods_free(*mod, True);
487 void talloc_autofree_ldapmod(TALLOC_CTX *mem_ctx, LDAPMod **mod)
495 handle = TALLOC_P(mem_ctx, LDAPMod **);
496 SMB_ASSERT(handle != NULL);
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)
515 /* sanity checks on the mod values */
517 if (attribute == NULL || *attribute == '\0') {
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')
528 mods = SMB_MALLOC_P(LDAPMod *);
530 smb_panic("smbldap_set_mod: out of memory!");
536 for (i = 0; mods[i] != NULL; ++i) {
537 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
541 if (mods[i] == NULL) {
542 mods = SMB_REALLOC_ARRAY (mods, LDAPMod *, i + 2);
544 smb_panic("smbldap_set_mod: out of memory!");
547 mods[i] = SMB_MALLOC_P(LDAPMod);
548 if (mods[i] == NULL) {
549 smb_panic("smbldap_set_mod: out of memory!");
552 mods[i]->mod_op = modop;
553 mods[i]->mod_values = NULL;
554 mods[i]->mod_type = SMB_STRDUP(attribute);
559 char *utf8_value = NULL;
560 size_t converted_size;
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!");
573 if (!push_utf8_talloc(talloc_tos(), &utf8_value, value, &converted_size)) {
574 smb_panic("smbldap_set_mod: String conversion failure!");
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;
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,
594 const char *attribute, const char *newval)
596 char oldval[2048]; /* current largest allowed value is mungeddial */
599 if (attribute == NULL) {
600 /* This can actually happen for ldapsam_compat where we for
601 * example don't have a password history */
605 if (existing != NULL) {
606 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval, sizeof(oldval));
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
619 DEBUG(10,("smbldap_make_mod: attribute |%s| not changed.\n", attribute));
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 {
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) {
669 return t->smbldap_state;
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);
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);
698 t = SMB_XMALLOC_P(struct smbldap_state_lookup);
701 DLIST_ADD_END(smbldap_state_lookup_list, t, struct smbldap_state_lookup *);
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
716 if (lp_ldap_ssl() != LDAP_SSL_START_TLS) {
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)));
732 DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
735 DEBUG(0,("StartTLS not supported by LDAP client libraries!\n"));
736 return LDAP_OPERATIONS_ERROR;
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)
748 DEBUG(10, ("smb_ldap_setup_connection: %s\n", uri));
750 #ifdef HAVE_LDAP_INITIALIZE
752 rc = ldap_initialize(ldap_struct, uri);
754 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(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)));
769 /* Parse the string manually */
775 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
778 /* skip leading "URL:" (if any) */
779 if ( strnequal( uri, "URL:", 4 ) ) {
783 sscanf(uri, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
786 if (strequal(protocol, "ldap")) {
788 } else if (strequal(protocol, "ldaps")) {
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"));
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 */
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)));
843 /********************************************************************
844 try to upgrade to Version 3 LDAP if not already, in either case return current
846 *******************************************************************/
848 static int smb_ldap_upgrade_conn(LDAP *ldap_struct, int *new_version)
853 /* assume the worst */
854 *new_version = LDAP_VERSION2;
856 rc = ldap_get_option(ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
861 if (version == LDAP_VERSION3) {
862 *new_version = LDAP_VERSION3;
867 version = LDAP_VERSION3;
868 rc = ldap_set_option (ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
873 *new_version = LDAP_VERSION3;
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)
885 rc = smb_ldap_setup_conn(ldap_struct, uri);
890 rc = smb_ldap_upgrade_conn(*ldap_struct, &version);
895 rc = smb_ldap_start_tls(*ldap_struct, version);
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;
912 LDAP **ldap_struct = &ldap_state->ldap_struct;
914 rc = smb_ldap_setup_conn(ldap_struct, ldap_state->uri);
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);
930 /* Start TLS if required */
932 rc = smb_ldap_start_tls(*ldap_struct, version);
937 /* Set alias dereferencing method */
938 deref = lp_ldap_deref();
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));
943 DEBUG(5,("Set dereferencing method: %d\n", deref));
947 DEBUG(2, ("smbldap_open_connection: connection opened\n"));
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)
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;
962 /** @TODO Should we be doing something to check what servers we rebind to?
963 Could we get a referral to a machine that we don't want to give our
964 username and password to? */
969 memset(*credp, '\0', strlen(*credp));
973 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n",
974 ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
976 if (ldap_state->anonymous) {
980 *whop = SMB_STRDUP(ldap_state->bind_dn);
982 return LDAP_NO_MEMORY;
984 *credp = SMB_STRDUP(ldap_state->bind_secret);
987 return LDAP_NO_MEMORY;
990 *methodp = LDAP_AUTH_SIMPLE;
993 GetTimeOfDay(&ldap_state->last_rebind);
997 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
999 /*******************************************************************
1000 a rebind function for authenticated referrals
1001 This version takes a void* that we can shove useful stuff in :-)
1002 and actually does the connection.
1003 ******************************************************************/
1004 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1005 static int rebindproc_connect_with_state (LDAP *ldap_struct,
1006 LDAP_CONST char *url,
1008 ber_int_t msgid, void *arg)
1010 struct smbldap_state *ldap_state =
1011 (struct smbldap_state *)arg;
1015 DEBUG(5,("rebindproc_connect_with_state: Rebinding to %s as \"%s\"\n",
1016 url, ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
1018 /* call START_TLS again (ldaps:// is handled by the OpenLDAP library
1019 * itself) before rebinding to another LDAP server to avoid to expose
1020 * our credentials. At least *try* to secure the connection - Guenther */
1022 smb_ldap_upgrade_conn(ldap_struct, &version);
1023 smb_ldap_start_tls(ldap_struct, version);
1025 /** @TODO Should we be doing something to check what servers we rebind to?
1026 Could we get a referral to a machine that we don't want to give our
1027 username and password to? */
1029 rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
1031 /* only set the last rebind timestamp when we did rebind after a
1032 * non-read LDAP operation. That way we avoid the replication sleep
1033 * after a simple redirected search operation - Guenther */
1037 case LDAP_REQ_MODIFY:
1039 case LDAP_REQ_DELETE:
1040 case LDAP_REQ_MODDN:
1041 case LDAP_REQ_EXTENDED:
1042 DEBUG(10,("rebindproc_connect_with_state: "
1043 "setting last_rebind timestamp "
1044 "(req: 0x%02x)\n", (unsigned int)request));
1045 GetTimeOfDay(&ldap_state->last_rebind);
1048 ZERO_STRUCT(ldap_state->last_rebind);
1054 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1056 /*******************************************************************
1057 Add a rebind function for authenticated referrals
1058 ******************************************************************/
1059 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1061 # if LDAP_SET_REBIND_PROC_ARGS == 2
1062 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
1063 int *method, int freeit )
1065 struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
1067 return rebindproc_with_state(ldap_struct, whop, credp,
1068 method, freeit, ldap_state);
1070 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
1071 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1073 /*******************************************************************
1074 a rebind function for authenticated referrals
1075 this also does the connection, but no void*.
1076 ******************************************************************/
1077 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1078 # if LDAP_SET_REBIND_PROC_ARGS == 2
1079 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
1082 struct smbldap_state *ldap_state = smbldap_find_state(ld);
1084 return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid,
1087 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
1088 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1090 /*******************************************************************
1091 connect to the ldap server under system privilege.
1092 ******************************************************************/
1093 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
1098 if (!ldap_state->anonymous && !ldap_state->bind_dn) {
1099 char *bind_dn = NULL;
1100 char *bind_secret = NULL;
1102 /* get the default dn and password only if they are not set already */
1103 if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
1104 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
1105 return LDAP_INVALID_CREDENTIALS;
1107 smbldap_set_creds(ldap_state, false, bind_dn, bind_secret);
1109 memset(bind_secret, '\0', strlen(bind_secret));
1110 SAFE_FREE(bind_secret);
1113 /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite
1114 (OpenLDAP) doesnt' seem to support it */
1116 DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
1117 ldap_state->uri, ldap_state->bind_dn));
1119 #ifdef HAVE_LDAP_SET_REBIND_PROC
1120 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1121 # if LDAP_SET_REBIND_PROC_ARGS == 2
1122 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect);
1124 # if LDAP_SET_REBIND_PROC_ARGS == 3
1125 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);
1127 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1128 # if LDAP_SET_REBIND_PROC_ARGS == 2
1129 ldap_set_rebind_proc(ldap_struct, &rebindproc);
1131 # if LDAP_SET_REBIND_PROC_ARGS == 3
1132 ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);
1134 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1137 rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
1139 if (rc != LDAP_SUCCESS) {
1140 char *ld_error = NULL;
1141 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1143 DEBUG(ldap_state->num_failures ? 2 : 0,
1144 ("failed to bind to server %s with dn=\"%s\" Error: %s\n\t%s\n",
1146 ldap_state->bind_dn ? ldap_state->bind_dn : "[Anonymous bind]",
1147 ldap_err2string(rc),
1148 ld_error ? ld_error : "(unknown)"));
1149 SAFE_FREE(ld_error);
1150 ldap_state->num_failures++;
1154 ldap_state->num_failures = 0;
1155 ldap_state->paged_results = False;
1157 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
1159 if (smbldap_has_control(ldap_state->ldap_struct, ADS_PAGE_CTL_OID) && version == 3) {
1160 ldap_state->paged_results = True;
1163 DEBUG(3, ("ldap_connect_system: successful connection to the LDAP server\n"));
1164 DEBUGADD(10, ("ldap_connect_system: LDAP server %s support paged results\n",
1165 ldap_state->paged_results ? "does" : "does not"));
1169 static void smbldap_idle_fn(struct event_context *event_ctx,
1170 struct timed_event *te,
1172 void *private_data);
1174 /**********************************************************************
1175 Connect to LDAP server (called before every ldap operation)
1176 *********************************************************************/
1177 static int smbldap_open(struct smbldap_state *ldap_state)
1180 bool reopen = False;
1181 SMB_ASSERT(ldap_state);
1183 if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
1185 #ifdef HAVE_UNIXSOCKET
1186 struct sockaddr_un addr;
1188 struct sockaddr addr;
1190 socklen_t len = sizeof(addr);
1193 opt_rc = ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd);
1194 if (opt_rc == 0 && (getpeername(sd, (struct sockaddr *) &addr, &len)) < 0 )
1197 #ifdef HAVE_UNIXSOCKET
1198 if (opt_rc == 0 && addr.sun_family == AF_UNIX)
1202 /* the other end has died. reopen. */
1203 ldap_unbind(ldap_state->ldap_struct);
1204 ldap_state->ldap_struct = NULL;
1205 ldap_state->last_ping = (time_t)0;
1207 ldap_state->last_ping = time(NULL);
1211 if (ldap_state->ldap_struct != NULL) {
1212 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
1213 return LDAP_SUCCESS;
1216 if ((rc = smbldap_open_connection(ldap_state))) {
1220 if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
1221 ldap_unbind(ldap_state->ldap_struct);
1222 ldap_state->ldap_struct = NULL;
1227 ldap_state->last_ping = time(NULL);
1228 ldap_state->pid = sys_getpid();
1230 TALLOC_FREE(ldap_state->idle_event);
1232 if (ldap_state->event_context != NULL) {
1233 ldap_state->idle_event = event_add_timed(
1234 ldap_state->event_context, NULL,
1235 timeval_current_ofs(SMBLDAP_IDLE_TIME, 0),
1236 smbldap_idle_fn, ldap_state);
1239 DEBUG(4,("The LDAP server is successfully connected\n"));
1241 return LDAP_SUCCESS;
1244 /**********************************************************************
1245 Disconnect from LDAP server
1246 *********************************************************************/
1247 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
1250 return NT_STATUS_INVALID_PARAMETER;
1252 if (ldap_state->ldap_struct != NULL) {
1253 ldap_unbind(ldap_state->ldap_struct);
1254 ldap_state->ldap_struct = NULL;
1257 smbldap_delete_state(ldap_state);
1259 DEBUG(5,("The connection to the LDAP server was closed\n"));
1260 /* maybe free the results here --metze */
1262 return NT_STATUS_OK;
1265 static bool got_alarm;
1267 static void (*old_handler)(int);
1269 static void gotalarm_sig(int dummy)
1274 static int another_ldap_try(struct smbldap_state *ldap_state, int *rc,
1275 int *attempts, time_t endtime)
1277 time_t now = time(NULL);
1278 int open_rc = LDAP_SERVER_DOWN;
1280 if (*rc != LDAP_SERVER_DOWN)
1283 if (now >= endtime) {
1284 smbldap_close(ldap_state);
1289 if (*attempts == 0) {
1291 old_handler = CatchSignal(SIGALRM, gotalarm_sig);
1292 alarm(endtime - now);
1294 if (ldap_state->pid != sys_getpid())
1295 smbldap_close(ldap_state);
1305 open_rc = smbldap_open(ldap_state);
1307 if (open_rc == LDAP_SUCCESS) {
1308 ldap_state->last_use = now;
1312 if (open_rc == LDAP_INSUFFICIENT_ACCESS) {
1313 /* The fact that we are non-root or any other
1314 * access-denied condition will not change in the next
1315 * round of trying */
1325 if (open_rc != LDAP_SUCCESS) {
1326 DEBUG(1, ("Connection to LDAP server failed for the "
1327 "%d try!\n", *attempts));
1332 CatchSignal(SIGALRM, old_handler);
1334 ldap_state->last_use = now;
1338 /*********************************************************************
1339 ********************************************************************/
1341 static int smbldap_search_ext(struct smbldap_state *ldap_state,
1342 const char *base, int scope, const char *filter,
1343 const char *attrs[], int attrsonly,
1344 LDAPControl **sctrls, LDAPControl **cctrls,
1345 int sizelimit, LDAPMessage **res)
1347 int rc = LDAP_SERVER_DOWN;
1350 time_t endtime = time(NULL)+lp_ldap_timeout();
1351 struct timeval timeout;
1352 size_t converted_size;
1354 SMB_ASSERT(ldap_state);
1356 DEBUG(5,("smbldap_search_ext: base => [%s], filter => [%s], "
1357 "scope => [%d]\n", base, filter, scope));
1359 if (ldap_state->last_rebind.tv_sec > 0) {
1360 struct timeval tval;
1365 GetTimeOfDay(&tval);
1367 tdiff = usec_time_diff(&tval, &ldap_state->last_rebind);
1368 tdiff /= 1000; /* Convert to milliseconds. */
1370 sleep_time = lp_ldap_replication_sleep()-(int)tdiff;
1371 sleep_time = MIN(sleep_time, MAX_LDAP_REPLICATION_SLEEP_TIME);
1373 if (sleep_time > 0) {
1374 /* we wait for the LDAP replication */
1375 DEBUG(5,("smbldap_search_ext: waiting %d milliseconds "
1376 "for LDAP replication.\n",sleep_time));
1377 smb_msleep(sleep_time);
1378 DEBUG(5,("smbldap_search_ext: go on!\n"));
1380 ZERO_STRUCT(ldap_state->last_rebind);
1383 if (!push_utf8_talloc(talloc_tos(), &utf8_filter, filter, &converted_size)) {
1384 return LDAP_NO_MEMORY;
1387 /* Setup timeout for the ldap_search_ext_s call - local and remote. */
1388 timeout.tv_sec = lp_ldap_timeout();
1389 timeout.tv_usec = 0;
1391 /* Setup alarm timeout.... Do we need both of these ? JRA.
1392 * Yes, I think we do need both of these. The server timeout only
1393 * covers the case where the server's operation takes too long. It
1394 * does not cover the case where the request hangs on its way to the
1395 * server. The server side timeout is not strictly necessary, it's
1396 * just a bit more kind to the server. VL. */
1399 CatchSignal(SIGALRM, gotalarm_sig);
1400 alarm(lp_ldap_timeout());
1401 /* End setup timeout. */
1403 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1404 rc = ldap_search_ext_s(ldap_state->ldap_struct, base, scope,
1406 CONST_DISCARD(char **, attrs),
1407 attrsonly, sctrls, cctrls, &timeout,
1409 if (rc != LDAP_SUCCESS) {
1410 char *ld_error = NULL;
1413 ldap_get_option(ldap_state->ldap_struct,
1414 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1416 ldap_get_option(ldap_state->ldap_struct,
1417 LDAP_OPT_ERROR_STRING, &ld_error);
1418 DEBUG(10, ("Failed search for base: %s, error: %d (%s) "
1419 "(%s)\n", base, ld_errno,
1420 ldap_err2string(rc),
1421 ld_error ? ld_error : "unknown"));
1422 SAFE_FREE(ld_error);
1424 if (ld_errno == LDAP_SERVER_DOWN) {
1425 ldap_unbind(ldap_state->ldap_struct);
1426 ldap_state->ldap_struct = NULL;
1431 TALLOC_FREE(utf8_filter);
1433 /* Teardown timeout. */
1434 CatchSignal(SIGALRM, SIG_IGN);
1438 return LDAP_TIMELIMIT_EXCEEDED;
1443 int smbldap_search(struct smbldap_state *ldap_state,
1444 const char *base, int scope, const char *filter,
1445 const char *attrs[], int attrsonly,
1448 return smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1449 attrsonly, NULL, NULL, LDAP_NO_LIMIT, res);
1452 int smbldap_search_paged(struct smbldap_state *ldap_state,
1453 const char *base, int scope, const char *filter,
1454 const char **attrs, int attrsonly, int pagesize,
1455 LDAPMessage **res, void **cookie)
1458 LDAPControl **rcontrols;
1459 LDAPControl *controls[2] = { NULL, NULL};
1460 BerElement *cookie_be = NULL;
1461 struct berval *cookie_bv = NULL;
1463 bool critical = True;
1467 DEBUG(3,("smbldap_search_paged: base => [%s], filter => [%s],"
1468 "scope => [%d], pagesize => [%d]\n",
1469 base, filter, scope, pagesize));
1471 cookie_be = ber_alloc_t(LBER_USE_DER);
1472 if (cookie_be == NULL) {
1473 DEBUG(0,("smbldap_create_page_control: ber_alloc_t returns "
1475 return LDAP_NO_MEMORY;
1478 /* construct cookie */
1479 if (*cookie != NULL) {
1480 ber_printf(cookie_be, "{iO}", (ber_int_t) pagesize, *cookie);
1481 ber_bvfree((struct berval *)*cookie); /* don't need it from last time */
1484 ber_printf(cookie_be, "{io}", (ber_int_t) pagesize, "", 0);
1486 ber_flatten(cookie_be, &cookie_bv);
1488 pr.ldctl_oid = CONST_DISCARD(char *, ADS_PAGE_CTL_OID);
1489 pr.ldctl_iscritical = (char) critical;
1490 pr.ldctl_value.bv_len = cookie_bv->bv_len;
1491 pr.ldctl_value.bv_val = cookie_bv->bv_val;
1496 rc = smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1497 0, controls, NULL, LDAP_NO_LIMIT, res);
1499 ber_free(cookie_be, 1);
1500 ber_bvfree(cookie_bv);
1503 DEBUG(3,("smbldap_search_paged: smbldap_search_ext(%s) "
1504 "failed with [%s]\n", filter, ldap_err2string(rc)));
1508 DEBUG(3,("smbldap_search_paged: search was successful\n"));
1510 rc = ldap_parse_result(ldap_state->ldap_struct, *res, NULL, NULL,
1511 NULL, NULL, &rcontrols, 0);
1513 DEBUG(3,("smbldap_search_paged: ldap_parse_result failed " \
1514 "with [%s]\n", ldap_err2string(rc)));
1518 if (rcontrols == NULL)
1521 for (i=0; rcontrols[i]; i++) {
1523 if (strcmp(ADS_PAGE_CTL_OID, rcontrols[i]->ldctl_oid) != 0)
1526 cookie_be = ber_init(&rcontrols[i]->ldctl_value);
1527 ber_scanf(cookie_be,"{iO}", &tmp, &cookie_bv);
1528 /* the berval is the cookie, but must be freed when it is all
1530 if (cookie_bv->bv_len)
1531 *cookie=ber_bvdup(cookie_bv);
1534 ber_bvfree(cookie_bv);
1535 ber_free(cookie_be, 1);
1538 ldap_controls_free(rcontrols);
1543 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1545 int rc = LDAP_SERVER_DOWN;
1548 time_t endtime = time(NULL)+lp_ldap_timeout();
1549 size_t converted_size;
1551 SMB_ASSERT(ldap_state);
1553 DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1555 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1556 return LDAP_NO_MEMORY;
1559 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1560 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1561 if (rc != LDAP_SUCCESS) {
1562 char *ld_error = NULL;
1565 ldap_get_option(ldap_state->ldap_struct,
1566 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1568 ldap_get_option(ldap_state->ldap_struct,
1569 LDAP_OPT_ERROR_STRING, &ld_error);
1570 DEBUG(10, ("Failed to modify dn: %s, error: %d (%s) "
1571 "(%s)\n", dn, ld_errno,
1572 ldap_err2string(rc),
1573 ld_error ? ld_error : "unknown"));
1574 SAFE_FREE(ld_error);
1576 if (ld_errno == LDAP_SERVER_DOWN) {
1577 ldap_unbind(ldap_state->ldap_struct);
1578 ldap_state->ldap_struct = NULL;
1583 TALLOC_FREE(utf8_dn);
1587 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1589 int rc = LDAP_SERVER_DOWN;
1592 time_t endtime = time(NULL)+lp_ldap_timeout();
1593 size_t converted_size;
1595 SMB_ASSERT(ldap_state);
1597 DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1599 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1600 return LDAP_NO_MEMORY;
1603 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1604 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1605 if (rc != LDAP_SUCCESS) {
1606 char *ld_error = NULL;
1609 ldap_get_option(ldap_state->ldap_struct,
1610 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1612 ldap_get_option(ldap_state->ldap_struct,
1613 LDAP_OPT_ERROR_STRING, &ld_error);
1614 DEBUG(10, ("Failed to add dn: %s, error: %d (%s) "
1615 "(%s)\n", dn, ld_errno,
1616 ldap_err2string(rc),
1617 ld_error ? ld_error : "unknown"));
1618 SAFE_FREE(ld_error);
1620 if (ld_errno == LDAP_SERVER_DOWN) {
1621 ldap_unbind(ldap_state->ldap_struct);
1622 ldap_state->ldap_struct = NULL;
1627 TALLOC_FREE(utf8_dn);
1631 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1633 int rc = LDAP_SERVER_DOWN;
1636 time_t endtime = time(NULL)+lp_ldap_timeout();
1637 size_t converted_size;
1639 SMB_ASSERT(ldap_state);
1641 DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1643 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1644 return LDAP_NO_MEMORY;
1647 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1648 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1649 if (rc != LDAP_SUCCESS) {
1650 char *ld_error = NULL;
1653 ldap_get_option(ldap_state->ldap_struct,
1654 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1656 ldap_get_option(ldap_state->ldap_struct,
1657 LDAP_OPT_ERROR_STRING, &ld_error);
1658 DEBUG(10, ("Failed to delete dn: %s, error: %d (%s) "
1659 "(%s)\n", dn, ld_errno,
1660 ldap_err2string(rc),
1661 ld_error ? ld_error : "unknown"));
1662 SAFE_FREE(ld_error);
1664 if (ld_errno == LDAP_SERVER_DOWN) {
1665 ldap_unbind(ldap_state->ldap_struct);
1666 ldap_state->ldap_struct = NULL;
1671 TALLOC_FREE(utf8_dn);
1675 int smbldap_extended_operation(struct smbldap_state *ldap_state,
1676 LDAP_CONST char *reqoid, struct berval *reqdata,
1677 LDAPControl **serverctrls, LDAPControl **clientctrls,
1678 char **retoidp, struct berval **retdatap)
1680 int rc = LDAP_SERVER_DOWN;
1682 time_t endtime = time(NULL)+lp_ldap_timeout();
1687 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1688 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid,
1689 reqdata, serverctrls,
1690 clientctrls, retoidp, retdatap);
1691 if (rc != LDAP_SUCCESS) {
1692 char *ld_error = NULL;
1695 ldap_get_option(ldap_state->ldap_struct,
1696 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1698 ldap_get_option(ldap_state->ldap_struct,
1699 LDAP_OPT_ERROR_STRING, &ld_error);
1700 DEBUG(10, ("Extended operation failed with error: "
1701 "%d (%s) (%s)\n", ld_errno,
1702 ldap_err2string(rc),
1703 ld_error ? ld_error : "unknown"));
1704 SAFE_FREE(ld_error);
1706 if (ld_errno == LDAP_SERVER_DOWN) {
1707 ldap_unbind(ldap_state->ldap_struct);
1708 ldap_state->ldap_struct = NULL;
1716 /*******************************************************************
1717 run the search by name.
1718 ******************************************************************/
1719 int smbldap_search_suffix (struct smbldap_state *ldap_state,
1720 const char *filter, const char **search_attr,
1721 LDAPMessage ** result)
1723 return smbldap_search(ldap_state, lp_ldap_suffix(), LDAP_SCOPE_SUBTREE,
1724 filter, search_attr, 0, result);
1727 static void smbldap_idle_fn(struct event_context *event_ctx,
1728 struct timed_event *te,
1732 struct smbldap_state *state = (struct smbldap_state *)private_data;
1734 TALLOC_FREE(state->idle_event);
1736 if (state->ldap_struct == NULL) {
1737 DEBUG(10,("ldap connection not connected...\n"));
1741 if ((state->last_use+SMBLDAP_IDLE_TIME) > now.tv_sec) {
1742 DEBUG(10,("ldap connection not idle...\n"));
1744 state->idle_event = event_add_timed(
1746 timeval_add(&now, SMBLDAP_IDLE_TIME, 0),
1752 DEBUG(7,("ldap connection idle...closing connection\n"));
1753 smbldap_close(state);
1756 /**********************************************************************
1758 *********************************************************************/
1760 void smbldap_free_struct(struct smbldap_state **ldap_state)
1762 smbldap_close(*ldap_state);
1764 if ((*ldap_state)->bind_secret) {
1765 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1768 SAFE_FREE((*ldap_state)->bind_dn);
1769 SAFE_FREE((*ldap_state)->bind_secret);
1771 TALLOC_FREE((*ldap_state)->idle_event);
1775 /* No need to free any further, as it is talloc()ed */
1779 /**********************************************************************
1780 Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1781 *********************************************************************/
1783 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, struct event_context *event_ctx,
1784 const char *location,
1785 struct smbldap_state **smbldap_state)
1787 *smbldap_state = TALLOC_ZERO_P(mem_ctx, struct smbldap_state);
1788 if (!*smbldap_state) {
1789 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1790 return NT_STATUS_NO_MEMORY;
1794 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1796 (*smbldap_state)->uri = "ldap://localhost";
1799 (*smbldap_state)->event_context = event_ctx;
1801 return NT_STATUS_OK;
1804 char *smbldap_talloc_dn(TALLOC_CTX *mem_ctx, LDAP *ld,
1807 char *utf8_dn, *unix_dn;
1808 size_t converted_size;
1810 utf8_dn = ldap_get_dn(ld, entry);
1812 DEBUG (5, ("smbldap_talloc_dn: ldap_get_dn failed\n"));
1815 if (!pull_utf8_talloc(mem_ctx, &unix_dn, utf8_dn, &converted_size)) {
1816 DEBUG (0, ("smbldap_talloc_dn: String conversion failure utf8 "
1817 "[%s]\n", utf8_dn));
1820 ldap_memfree(utf8_dn);
1824 /*******************************************************************
1825 Check if root-dse has a certain Control or Extension
1826 ********************************************************************/
1828 static bool smbldap_check_root_dse(LDAP *ld, const char **attrs, const char *value)
1830 LDAPMessage *msg = NULL;
1831 LDAPMessage *entry = NULL;
1832 char **values = NULL;
1833 int rc, num_result, num_values, i;
1834 bool result = False;
1837 DEBUG(3,("smbldap_check_root_dse: nothing to look for\n"));
1841 if (!strequal(attrs[0], "supportedExtension") &&
1842 !strequal(attrs[0], "supportedControl") &&
1843 !strequal(attrs[0], "namingContexts")) {
1844 DEBUG(3,("smbldap_check_root_dse: no idea what to query root-dse for: %s ?\n", attrs[0]));
1848 rc = ldap_search_s(ld, "", LDAP_SCOPE_BASE,
1849 "(objectclass=*)", CONST_DISCARD(char **, attrs), 0 , &msg);
1851 if (rc != LDAP_SUCCESS) {
1852 DEBUG(3,("smbldap_check_root_dse: Could not search rootDSE\n"));
1856 num_result = ldap_count_entries(ld, msg);
1858 if (num_result != 1) {
1859 DEBUG(3,("smbldap_check_root_dse: Expected one rootDSE, got %d\n", num_result));
1863 entry = ldap_first_entry(ld, msg);
1865 if (entry == NULL) {
1866 DEBUG(3,("smbldap_check_root_dse: Could not retrieve rootDSE\n"));
1870 values = ldap_get_values(ld, entry, attrs[0]);
1872 if (values == NULL) {
1873 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not support any %s\n", attrs[0]));
1877 num_values = ldap_count_values(values);
1879 if (num_values == 0) {
1880 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not have any %s\n", attrs[0]));
1884 for (i=0; i<num_values; i++) {
1885 if (strcmp(values[i], value) == 0)
1892 ldap_value_free(values);
1900 /*******************************************************************
1901 Check if LDAP-Server supports a certain Control (OID in string format)
1902 ********************************************************************/
1904 bool smbldap_has_control(LDAP *ld, const char *control)
1906 const char *attrs[] = { "supportedControl", NULL };
1907 return smbldap_check_root_dse(ld, attrs, control);
1910 /*******************************************************************
1911 Check if LDAP-Server supports a certain Extension (OID in string format)
1912 ********************************************************************/
1914 bool smbldap_has_extension(LDAP *ld, const char *extension)
1916 const char *attrs[] = { "supportedExtension", NULL };
1917 return smbldap_check_root_dse(ld, attrs, extension);
1920 /*******************************************************************
1921 Check if LDAP-Server holds a given namingContext
1922 ********************************************************************/
1924 bool smbldap_has_naming_context(LDAP *ld, const char *naming_context)
1926 const char *attrs[] = { "namingContexts", NULL };
1927 return smbldap_check_root_dse(ld, attrs, naming_context);
1930 bool smbldap_set_creds(struct smbldap_state *ldap_state, bool anon, const char *dn, const char *secret)
1932 ldap_state->anonymous = anon;
1934 /* free any previously set credential */
1936 SAFE_FREE(ldap_state->bind_dn);
1937 if (ldap_state->bind_secret) {
1938 /* make sure secrets are zeroed out of memory */
1939 memset(ldap_state->bind_secret, '\0', strlen(ldap_state->bind_secret));
1940 SAFE_FREE(ldap_state->bind_secret);
1944 ldap_state->bind_dn = SMB_STRDUP(dn);
1945 ldap_state->bind_secret = SMB_STRDUP(secret);