2 Unix SMB/CIFS implementation.
3 LDAP protocol helper functions for SAMBA
4 Copyright (C) Jean François Micouleau 1998
5 Copyright (C) Gerald Carter 2001-2003
6 Copyright (C) Shahms King 2001
7 Copyright (C) Andrew Bartlett 2002-2003
8 Copyright (C) Stefan (metze) Metzmacher 2002-2003
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #ifndef LDAP_OPT_SUCCESS
30 #define LDAP_OPT_SUCCESS 0
33 /* Try not to hit the up or down server forever */
35 #define SMBLDAP_DONT_PING_TIME 10 /* ping only all 10 seconds */
36 #define SMBLDAP_NUM_RETRIES 8 /* retry only 8 times */
38 #define SMBLDAP_IDLE_TIME 150 /* After 2.5 minutes disconnect */
41 /* attributes used by Samba 2.2 */
43 ATTRIB_MAP_ENTRY attrib_map_v22[] = {
44 { LDAP_ATTR_UID, "uid" },
45 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
46 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
47 { LDAP_ATTR_UNIX_HOME, "homeDirectory" },
48 { LDAP_ATTR_PWD_LAST_SET, "pwdLastSet" },
49 { LDAP_ATTR_PWD_CAN_CHANGE, "pwdCanChange" },
50 { LDAP_ATTR_PWD_MUST_CHANGE, "pwdMustChange" },
51 { LDAP_ATTR_LOGON_TIME, "logonTime" },
52 { LDAP_ATTR_LOGOFF_TIME, "logoffTime" },
53 { LDAP_ATTR_KICKOFF_TIME, "kickoffTime" },
54 { LDAP_ATTR_CN, "cn" },
55 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
56 { LDAP_ATTR_HOME_PATH, "smbHome" },
57 { LDAP_ATTR_HOME_DRIVE, "homeDrive" },
58 { LDAP_ATTR_LOGON_SCRIPT, "scriptPath" },
59 { LDAP_ATTR_PROFILE_PATH, "profilePath" },
60 { LDAP_ATTR_DESC, "description" },
61 { LDAP_ATTR_USER_WKS, "userWorkstations"},
62 { LDAP_ATTR_USER_RID, "rid" },
63 { LDAP_ATTR_PRIMARY_GROUP_RID, "primaryGroupID"},
64 { LDAP_ATTR_LMPW, "lmPassword" },
65 { LDAP_ATTR_NTPW, "ntPassword" },
66 { LDAP_ATTR_DOMAIN, "domain" },
67 { LDAP_ATTR_OBJCLASS, "objectClass" },
68 { LDAP_ATTR_ACB_INFO, "acctFlags" },
69 { LDAP_ATTR_MOD_TIMESTAMP, "modifyTimestamp" },
70 { LDAP_ATTR_LIST_END, NULL }
73 ATTRIB_MAP_ENTRY attrib_map_to_delete_v22[] = {
74 { LDAP_ATTR_PWD_LAST_SET, "pwdLastSet" },
75 { LDAP_ATTR_PWD_CAN_CHANGE, "pwdCanChange" },
76 { LDAP_ATTR_PWD_MUST_CHANGE, "pwdMustChange" },
77 { LDAP_ATTR_LOGON_TIME, "logonTime" },
78 { LDAP_ATTR_LOGOFF_TIME, "logoffTime" },
79 { LDAP_ATTR_KICKOFF_TIME, "kickoffTime" },
80 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
81 { LDAP_ATTR_HOME_PATH, "smbHome" },
82 { LDAP_ATTR_HOME_DRIVE, "homeDrives" },
83 { LDAP_ATTR_LOGON_SCRIPT, "scriptPath" },
84 { LDAP_ATTR_PROFILE_PATH, "profilePath" },
85 { LDAP_ATTR_USER_WKS, "userWorkstations"},
86 { LDAP_ATTR_USER_RID, "rid" },
87 { LDAP_ATTR_PRIMARY_GROUP_RID, "primaryGroupID"},
88 { LDAP_ATTR_LMPW, "lmPassword" },
89 { LDAP_ATTR_NTPW, "ntPassword" },
90 { LDAP_ATTR_DOMAIN, "domain" },
91 { LDAP_ATTR_ACB_INFO, "acctFlags" },
92 { LDAP_ATTR_LIST_END, NULL }
95 /* attributes used by Samba 3.0's sambaSamAccount */
97 ATTRIB_MAP_ENTRY attrib_map_v30[] = {
98 { LDAP_ATTR_UID, "uid" },
99 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
100 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
101 { LDAP_ATTR_UNIX_HOME, "homeDirectory" },
102 { LDAP_ATTR_PWD_LAST_SET, "sambaPwdLastSet" },
103 { LDAP_ATTR_PWD_CAN_CHANGE, "sambaPwdCanChange" },
104 { LDAP_ATTR_PWD_MUST_CHANGE, "sambaPwdMustChange" },
105 { LDAP_ATTR_LOGON_TIME, "sambaLogonTime" },
106 { LDAP_ATTR_LOGOFF_TIME, "sambaLogoffTime" },
107 { LDAP_ATTR_KICKOFF_TIME, "sambaKickoffTime" },
108 { LDAP_ATTR_CN, "cn" },
109 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
110 { LDAP_ATTR_HOME_DRIVE, "sambaHomeDrive" },
111 { LDAP_ATTR_HOME_PATH, "sambaHomePath" },
112 { LDAP_ATTR_LOGON_SCRIPT, "sambaLogonScript" },
113 { LDAP_ATTR_PROFILE_PATH, "sambaProfilePath" },
114 { LDAP_ATTR_DESC, "description" },
115 { LDAP_ATTR_USER_WKS, "sambaUserWorkstations" },
116 { LDAP_ATTR_USER_SID, LDAP_ATTRIBUTE_SID },
117 { LDAP_ATTR_PRIMARY_GROUP_SID, "sambaPrimaryGroupSID" },
118 { LDAP_ATTR_LMPW, "sambaLMPassword" },
119 { LDAP_ATTR_NTPW, "sambaNTPassword" },
120 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
121 { LDAP_ATTR_OBJCLASS, "objectClass" },
122 { LDAP_ATTR_ACB_INFO, "sambaAcctFlags" },
123 { LDAP_ATTR_MUNGED_DIAL, "sambaMungedDial" },
124 { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
125 { LDAP_ATTR_BAD_PASSWORD_TIME, "sambaBadPasswordTime" },
126 { LDAP_ATTR_PWD_HISTORY, "sambaPasswordHistory" },
127 { LDAP_ATTR_MOD_TIMESTAMP, "modifyTimestamp" },
128 { LDAP_ATTR_LOGON_HOURS, "sambaLogonHours" },
129 { LDAP_ATTR_LIST_END, NULL }
132 ATTRIB_MAP_ENTRY attrib_map_to_delete_v30[] = {
133 { LDAP_ATTR_PWD_LAST_SET, "sambaPwdLastSet" },
134 { LDAP_ATTR_PWD_CAN_CHANGE, "sambaPwdCanChange" },
135 { LDAP_ATTR_PWD_MUST_CHANGE, "sambaPwdMustChange" },
136 { LDAP_ATTR_LOGON_TIME, "sambaLogonTime" },
137 { LDAP_ATTR_LOGOFF_TIME, "sambaLogoffTime" },
138 { LDAP_ATTR_KICKOFF_TIME, "sambaKickoffTime" },
139 { LDAP_ATTR_HOME_DRIVE, "sambaHomeDrive" },
140 { LDAP_ATTR_HOME_PATH, "sambaHomePath" },
141 { LDAP_ATTR_LOGON_SCRIPT, "sambaLogonScript" },
142 { LDAP_ATTR_PROFILE_PATH, "sambaProfilePath" },
143 { LDAP_ATTR_USER_WKS, "sambaUserWorkstations" },
144 { LDAP_ATTR_USER_SID, LDAP_ATTRIBUTE_SID },
145 { LDAP_ATTR_PRIMARY_GROUP_SID, "sambaPrimaryGroupSID" },
146 { LDAP_ATTR_LMPW, "sambaLMPassword" },
147 { LDAP_ATTR_NTPW, "sambaNTPassword" },
148 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
149 { LDAP_ATTR_ACB_INFO, "sambaAcctFlags" },
150 { LDAP_ATTR_MUNGED_DIAL, "sambaMungedDial" },
151 { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
152 { LDAP_ATTR_BAD_PASSWORD_TIME, "sambaBadPasswordTime" },
153 { LDAP_ATTR_PWD_HISTORY, "sambaPasswordHistory" },
154 { LDAP_ATTR_LOGON_HOURS, "sambaLogonHours" },
155 { LDAP_ATTR_LIST_END, NULL }
158 /* attributes used for allocating RIDs */
160 ATTRIB_MAP_ENTRY dominfo_attr_list[] = {
161 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
162 { LDAP_ATTR_NEXT_RID, "sambaNextRid" },
163 { LDAP_ATTR_NEXT_USERRID, "sambaNextUserRid" },
164 { LDAP_ATTR_NEXT_GROUPRID, "sambaNextGroupRid" },
165 { LDAP_ATTR_DOM_SID, LDAP_ATTRIBUTE_SID },
166 { LDAP_ATTR_ALGORITHMIC_RID_BASE,"sambaAlgorithmicRidBase"},
167 { LDAP_ATTR_OBJCLASS, "objectClass" },
168 { LDAP_ATTR_LIST_END, NULL },
171 /* Samba 3.0 group mapping attributes */
173 ATTRIB_MAP_ENTRY groupmap_attr_list[] = {
174 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
175 { LDAP_ATTR_GROUP_SID, LDAP_ATTRIBUTE_SID },
176 { LDAP_ATTR_GROUP_TYPE, "sambaGroupType" },
177 { LDAP_ATTR_SID_LIST, "sambaSIDList" },
178 { LDAP_ATTR_DESC, "description" },
179 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
180 { LDAP_ATTR_CN, "cn" },
181 { LDAP_ATTR_OBJCLASS, "objectClass" },
182 { LDAP_ATTR_LIST_END, NULL }
185 ATTRIB_MAP_ENTRY groupmap_attr_list_to_delete[] = {
186 { LDAP_ATTR_GROUP_SID, LDAP_ATTRIBUTE_SID },
187 { LDAP_ATTR_GROUP_TYPE, "sambaGroupType" },
188 { LDAP_ATTR_DESC, "description" },
189 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
190 { LDAP_ATTR_SID_LIST, "sambaSIDList" },
191 { LDAP_ATTR_LIST_END, NULL }
194 /* idmap_ldap sambaUnixIdPool */
196 ATTRIB_MAP_ENTRY idpool_attr_list[] = {
197 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
198 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
199 { LDAP_ATTR_OBJCLASS, "objectClass" },
200 { LDAP_ATTR_LIST_END, NULL }
203 ATTRIB_MAP_ENTRY sidmap_attr_list[] = {
204 { LDAP_ATTR_SID, LDAP_ATTRIBUTE_SID },
205 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
206 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
207 { LDAP_ATTR_OBJCLASS, "objectClass" },
208 { LDAP_ATTR_LIST_END, NULL }
211 /**********************************************************************
212 perform a simple table lookup and return the attribute name
213 **********************************************************************/
215 const char* get_attr_key2string( ATTRIB_MAP_ENTRY table[], int key )
219 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
220 if ( table[i].attrib == key )
221 return table[i].name;
229 /**********************************************************************
230 Return the list of attribute names from a mapping table
231 **********************************************************************/
233 const char** get_attr_list( ATTRIB_MAP_ENTRY table[] )
238 while ( table[i].attrib != LDAP_ATTR_LIST_END )
242 names = SMB_MALLOC_ARRAY( const char*, i );
244 DEBUG(0,("get_attr_list: out of memory\n"));
249 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
250 names[i] = SMB_STRDUP( table[i].name );
258 /*********************************************************************
260 ********************************************************************/
262 void free_attr_list( const char **list )
270 SAFE_FREE( list[i] );
277 /*******************************************************************
278 find the ldap password
279 ******************************************************************/
280 static BOOL fetch_ldap_pw(char **dn, char** pw)
285 *dn = smb_xstrdup(lp_ldap_admin_dn());
287 if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, *dn) < 0) {
289 DEBUG(0, ("fetch_ldap_pw: asprintf failed!\n"));
292 *pw=secrets_fetch(key, &size);
296 /* Upgrade 2.2 style entry */
298 char* old_style_key = SMB_STRDUP(*dn);
300 fstring old_style_pw;
302 if (!old_style_key) {
303 DEBUG(0, ("fetch_ldap_pw: strdup failed!\n"));
307 for (p=old_style_key; *p; p++)
308 if (*p == ',') *p = '/';
310 data=secrets_fetch(old_style_key, &size);
311 if (!size && size < sizeof(old_style_pw)) {
312 DEBUG(0,("fetch_ldap_pw: neither ldap secret retrieved!\n"));
313 SAFE_FREE(old_style_key);
318 size = MIN(size, sizeof(fstring)-1);
319 strncpy(old_style_pw, data, size);
320 old_style_pw[size] = 0;
324 if (!secrets_store_ldap_pw(*dn, old_style_pw)) {
325 DEBUG(0,("fetch_ldap_pw: ldap secret could not be upgraded!\n"));
326 SAFE_FREE(old_style_key);
330 if (!secrets_delete(old_style_key)) {
331 DEBUG(0,("fetch_ldap_pw: old ldap secret could not be deleted!\n"));
334 SAFE_FREE(old_style_key);
336 *pw = smb_xstrdup(old_style_pw);
342 /*******************************************************************
343 Search an attribute and return the first value found.
344 ******************************************************************/
346 BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
347 const char *attribute, char *value,
357 if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
358 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
363 if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, max_len, False) == (size_t)-1) {
364 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n",
365 attribute, values[0]));
366 ldap_value_free(values);
370 ldap_value_free(values);
371 #ifdef DEBUG_PASSWORDS
372 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
377 BOOL smbldap_get_single_pstring (LDAP * ldap_struct, LDAPMessage * entry,
378 const char *attribute, pstring value)
380 return smbldap_get_single_attribute(ldap_struct, entry,
385 /************************************************************************
386 Routine to manage the LDAPMod structure array
387 manage memory used by the array, by each struct, and values
388 ***********************************************************************/
390 void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
398 /* sanity checks on the mod values */
400 if (attribute == NULL || *attribute == '\0') {
404 #if 0 /* commented out after discussion with abartlet. Do not reenable.
405 left here so other so re-add similar code --jerry */
406 if (value == NULL || *value == '\0')
411 mods = SMB_MALLOC_P(LDAPMod *);
413 DEBUG(0, ("make_a_mod: out of memory!\n"));
419 for (i = 0; mods[i] != NULL; ++i) {
420 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
424 if (mods[i] == NULL) {
425 mods = SMB_REALLOC_ARRAY (mods, LDAPMod *, i + 2);
427 DEBUG(0, ("make_a_mod: out of memory!\n"));
430 mods[i] = SMB_MALLOC_P(LDAPMod);
431 if (mods[i] == NULL) {
432 DEBUG(0, ("make_a_mod: out of memory!\n"));
435 mods[i]->mod_op = modop;
436 mods[i]->mod_values = NULL;
437 mods[i]->mod_type = SMB_STRDUP(attribute);
442 char *utf8_value = NULL;
445 if (mods[i]->mod_values != NULL) {
446 for (; mods[i]->mod_values[j] != NULL; j++);
448 mods[i]->mod_values = SMB_REALLOC_ARRAY(mods[i]->mod_values, char *, j + 2);
450 if (mods[i]->mod_values == NULL) {
451 DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
455 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
456 DEBUG (0, ("make_a_mod: String conversion failure!\n"));
460 mods[i]->mod_values[j] = utf8_value;
462 mods[i]->mod_values[j + 1] = NULL;
467 /**********************************************************************
468 Set attribute to newval in LDAP, regardless of what value the
469 attribute had in LDAP before.
470 *********************************************************************/
472 void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
474 const char *attribute, const char *newval)
476 char oldval[2048]; /* current largest allowed value is mungeddial */
479 if (attribute == NULL) {
480 /* This can actually happen for ldapsam_compat where we for
481 * example don't have a password history */
485 if (existing != NULL) {
486 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval, sizeof(oldval));
492 /* all of our string attributes are case insensitive */
494 if (existed && newval && (StrCaseCmp(oldval, newval) == 0)) {
496 /* Believe it or not, but LDAP will deny a delete and
497 an add at the same time if the values are the
503 /* There has been no value before, so don't delete it.
504 * Here's a possible race: We might end up with
505 * duplicate attributes */
506 /* By deleting exactly the value we found in the entry this
507 * should be race-free in the sense that the LDAP-Server will
508 * deny the complete operation if somebody changed the
509 * attribute behind our back. */
510 /* This will also allow modifying single valued attributes
511 * in Novell NDS. In NDS you have to first remove attribute and then
512 * you could add new value */
514 smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, oldval);
517 /* Regardless of the real operation (add or modify)
518 we add the new value here. We rely on deleting
519 the old value, should it exist. */
521 if ((newval != NULL) && (strlen(newval) > 0)) {
522 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
526 /**********************************************************************
527 Some varients of the LDAP rebind code do not pass in the third 'arg'
528 pointer to a void*, so we try and work around it by assuming that the
529 value of the 'LDAP *' pointer is the same as the one we had passed in
530 **********************************************************************/
532 struct smbldap_state_lookup {
534 struct smbldap_state *smbldap_state;
535 struct smbldap_state_lookup *prev, *next;
538 static struct smbldap_state_lookup *smbldap_state_lookup_list;
540 static struct smbldap_state *smbldap_find_state(LDAP *ld)
542 struct smbldap_state_lookup *t;
544 for (t = smbldap_state_lookup_list; t; t = t->next) {
546 return t->smbldap_state;
552 static void smbldap_delete_state(struct smbldap_state *smbldap_state)
554 struct smbldap_state_lookup *t;
556 for (t = smbldap_state_lookup_list; t; t = t->next) {
557 if (t->smbldap_state == smbldap_state) {
558 DLIST_REMOVE(smbldap_state_lookup_list, t);
565 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state)
567 struct smbldap_state *tmp_ldap_state;
568 struct smbldap_state_lookup *t;
569 struct smbldap_state_lookup *tmp;
571 if ((tmp_ldap_state = smbldap_find_state(ld))) {
572 SMB_ASSERT(tmp_ldap_state == smbldap_state);
576 t = SMB_XMALLOC_P(struct smbldap_state_lookup);
579 DLIST_ADD_END(smbldap_state_lookup_list, t, tmp);
581 t->smbldap_state = smbldap_state;
584 /*******************************************************************
585 open a connection to the ldap server.
586 ******************************************************************/
587 static int smbldap_open_connection (struct smbldap_state *ldap_state)
590 int rc = LDAP_SUCCESS;
592 BOOL ldap_v3 = False;
593 LDAP **ldap_struct = &ldap_state->ldap_struct;
595 #ifdef HAVE_LDAP_INITIALIZE
596 DEBUG(10, ("smbldap_open_connection: %s\n", ldap_state->uri));
598 if ((rc = ldap_initialize(ldap_struct, ldap_state->uri)) != LDAP_SUCCESS) {
599 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
604 /* Parse the string manually */
610 const char *p = ldap_state->uri;
611 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
613 /* skip leading "URL:" (if any) */
614 if ( strnequal( p, "URL:", 4 ) ) {
618 sscanf(p, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
621 if (strequal(protocol, "ldap")) {
623 } else if (strequal(protocol, "ldaps")) {
626 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
630 if ((*ldap_struct = ldap_init(host, port)) == NULL) {
631 DEBUG(0, ("ldap_init failed !\n"));
632 return LDAP_OPERATIONS_ERROR;
635 if (strequal(protocol, "ldaps")) {
636 #ifdef LDAP_OPT_X_TLS
637 int tls = LDAP_OPT_X_TLS_HARD;
638 if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
640 DEBUG(0, ("Failed to setup a TLS session\n"));
643 DEBUG(3,("LDAPS option set...!\n"));
645 DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
646 return LDAP_OPERATIONS_ERROR;
652 /* Store the LDAP pointer in a lookup list */
654 smbldap_store_state(*ldap_struct, ldap_state);
656 /* Upgrade to LDAPv3 if possible */
658 if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
660 if (version != LDAP_VERSION3)
662 version = LDAP_VERSION3;
663 if (ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS) {
671 if (lp_ldap_ssl() == LDAP_SSL_START_TLS) {
672 #ifdef LDAP_OPT_X_TLS
674 if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
676 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
677 ldap_err2string(rc)));
680 DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
683 DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
684 return LDAP_OPERATIONS_ERROR;
687 DEBUG(0,("smbldap_open_connection: StartTLS not supported by LDAP client libraries!\n"));
688 return LDAP_OPERATIONS_ERROR;
692 DEBUG(2, ("smbldap_open_connection: connection opened\n"));
697 /*******************************************************************
698 a rebind function for authenticated referrals
699 This version takes a void* that we can shove useful stuff in :-)
700 ******************************************************************/
701 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
703 static int rebindproc_with_state (LDAP * ld, char **whop, char **credp,
704 int *methodp, int freeit, void *arg)
706 struct smbldap_state *ldap_state = arg;
708 /** @TODO Should we be doing something to check what servers we rebind to?
709 Could we get a referral to a machine that we don't want to give our
710 username and password to? */
714 memset(*credp, '\0', strlen(*credp));
717 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n",
718 ldap_state->bind_dn));
720 *whop = SMB_STRDUP(ldap_state->bind_dn);
722 return LDAP_NO_MEMORY;
724 *credp = SMB_STRDUP(ldap_state->bind_secret);
727 return LDAP_NO_MEMORY;
729 *methodp = LDAP_AUTH_SIMPLE;
732 GetTimeOfDay(&ldap_state->last_rebind);
736 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
738 /*******************************************************************
739 a rebind function for authenticated referrals
740 This version takes a void* that we can shove useful stuff in :-)
741 and actually does the connection.
742 ******************************************************************/
743 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
744 static int rebindproc_connect_with_state (LDAP *ldap_struct,
745 LDAP_CONST char *url,
747 ber_int_t msgid, void *arg)
749 struct smbldap_state *ldap_state = arg;
751 DEBUG(5,("rebindproc_connect_with_state: Rebinding as \"%s\"\n",
752 ldap_state->bind_dn));
754 /** @TODO Should we be doing something to check what servers we rebind to?
755 Could we get a referral to a machine that we don't want to give our
756 username and password to? */
758 rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
760 GetTimeOfDay(&ldap_state->last_rebind);
764 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
766 /*******************************************************************
767 Add a rebind function for authenticated referrals
768 ******************************************************************/
769 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
771 # if LDAP_SET_REBIND_PROC_ARGS == 2
772 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
773 int *method, int freeit )
775 struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
777 return rebindproc_with_state(ldap_struct, whop, credp,
778 method, freeit, ldap_state);
781 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
782 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
784 /*******************************************************************
785 a rebind function for authenticated referrals
786 this also does the connection, but no void*.
787 ******************************************************************/
788 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
789 # if LDAP_SET_REBIND_PROC_ARGS == 2
790 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
793 struct smbldap_state *ldap_state = smbldap_find_state(ld);
795 return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid,
798 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
799 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
801 /*******************************************************************
802 connect to the ldap server under system privilege.
803 ******************************************************************/
804 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
811 /* get the password */
812 if (!fetch_ldap_pw(&ldap_dn, &ldap_secret)) {
813 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
814 return LDAP_INVALID_CREDENTIALS;
817 ldap_state->bind_dn = ldap_dn;
818 ldap_state->bind_secret = ldap_secret;
820 /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite
821 (OpenLDAP) doesnt' seem to support it */
823 DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
824 ldap_state->uri, ldap_dn));
826 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
827 # if LDAP_SET_REBIND_PROC_ARGS == 2
828 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect);
830 # if LDAP_SET_REBIND_PROC_ARGS == 3
831 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);
833 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
834 # if LDAP_SET_REBIND_PROC_ARGS == 2
835 ldap_set_rebind_proc(ldap_struct, &rebindproc);
837 # if LDAP_SET_REBIND_PROC_ARGS == 3
838 ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);
840 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
842 rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
844 if (rc != LDAP_SUCCESS) {
845 char *ld_error = NULL;
846 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
848 DEBUG(ldap_state->num_failures ? 2 : 0,
849 ("failed to bind to server %s with dn=\"%s\" Error: %s\n\t%s\n",
851 ldap_dn ? ldap_dn : "(unknown)", ldap_err2string(rc),
852 ld_error ? ld_error : "(unknown)"));
854 ldap_state->num_failures++;
858 ldap_state->num_failures = 0;
859 ldap_state->paged_results = False;
861 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
863 if (smbldap_has_control(ldap_state, ADS_PAGE_CTL_OID) && version == 3) {
864 ldap_state->paged_results = True;
867 DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
868 DEBUGADD(10, ("ldap_connect_system: LDAP server %s support paged results\n",
869 ldap_state->paged_results ? "does" : "does not"));
873 /**********************************************************************
874 Connect to LDAP server (called before every ldap operation)
875 *********************************************************************/
876 static int smbldap_open(struct smbldap_state *ldap_state)
881 SMB_ASSERT(ldap_state);
882 #ifndef NO_LDAP_SECURITY
883 if (geteuid() != 0) {
884 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
885 return LDAP_INSUFFICIENT_ACCESS;
889 if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
891 struct sockaddr_un addr;
892 socklen_t len = sizeof(addr);
895 opt_rc = ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd);
896 if (opt_rc == 0 && (getpeername(sd, (struct sockaddr *) &addr, &len)) < 0 )
899 #ifdef HAVE_UNIXSOCKET
900 if (opt_rc == 0 && addr.sun_family == AF_UNIX)
904 /* the other end has died. reopen. */
905 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
906 ldap_state->ldap_struct = NULL;
907 ldap_state->last_ping = (time_t)0;
909 ldap_state->last_ping = time(NULL);
913 if (ldap_state->ldap_struct != NULL) {
914 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
918 if ((rc = smbldap_open_connection(ldap_state))) {
922 if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
923 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
924 ldap_state->ldap_struct = NULL;
929 ldap_state->last_ping = time(NULL);
930 ldap_state->pid = sys_getpid();
931 DEBUG(4,("The LDAP server is succesfully connected\n"));
936 /**********************************************************************
937 Disconnect from LDAP server
938 *********************************************************************/
939 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
942 return NT_STATUS_INVALID_PARAMETER;
944 if (ldap_state->ldap_struct != NULL) {
945 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
946 ldap_state->ldap_struct = NULL;
949 smbldap_delete_state(ldap_state);
951 DEBUG(5,("The connection to the LDAP server was closed\n"));
952 /* maybe free the results here --metze */
959 static BOOL got_alarm;
961 static void (*old_handler)(int);
963 static void gotalarm_sig(int dummy)
968 static int another_ldap_try(struct smbldap_state *ldap_state, int *rc,
969 int *attempts, time_t endtime)
971 time_t now = time(NULL);
972 int open_rc = LDAP_SERVER_DOWN;
974 if (*rc != LDAP_SERVER_DOWN)
977 if (now >= endtime) {
978 smbldap_close(ldap_state);
983 if (*attempts == 0) {
985 old_handler = CatchSignal(SIGALRM, gotalarm_sig);
986 alarm(endtime - now);
988 if (ldap_state->pid != sys_getpid())
989 smbldap_close(ldap_state);
999 open_rc = smbldap_open(ldap_state);
1001 if (open_rc == LDAP_SUCCESS) {
1002 ldap_state->last_use = now;
1011 if (open_rc != LDAP_SUCCESS) {
1012 DEBUG(1, ("Connection to LDAP server failed for the "
1013 "%d try!\n", *attempts));
1018 CatchSignal(SIGALRM, old_handler);
1020 ldap_state->last_use = now;
1024 /*********************************************************************
1025 ********************************************************************/
1027 static int smbldap_search_ext(struct smbldap_state *ldap_state,
1028 const char *base, int scope, const char *filter,
1029 const char *attrs[], int attrsonly,
1030 LDAPControl **sctrls, LDAPControl **cctrls,
1031 int sizelimit, LDAPMessage **res)
1033 int rc = LDAP_SERVER_DOWN;
1036 time_t endtime = time(NULL)+lp_ldap_timeout();
1037 struct timeval timeout;
1039 SMB_ASSERT(ldap_state);
1041 DEBUG(5,("smbldap_search_ext: base => [%s], filter => [%s], "
1042 "scope => [%d]\n", base, filter, scope));
1044 if (ldap_state->last_rebind.tv_sec > 0) {
1045 struct timeval tval;
1046 SMB_BIG_INT tdiff = 0;
1050 GetTimeOfDay(&tval);
1052 tdiff = usec_time_diff(&tval, &ldap_state->last_rebind);
1053 tdiff /= 1000; /* Convert to milliseconds. */
1055 sleep_time = lp_ldap_replication_sleep()-(int)tdiff;
1056 sleep_time = MIN(sleep_time, MAX_LDAP_REPLICATION_SLEEP_TIME);
1058 if (sleep_time > 0) {
1059 /* we wait for the LDAP replication */
1060 DEBUG(5,("smbldap_search_ext: waiting %d milliseconds "
1061 "for LDAP replication.\n",sleep_time));
1062 smb_msleep(sleep_time);
1063 DEBUG(5,("smbldap_search_ext: go on!\n"));
1065 ZERO_STRUCT(ldap_state->last_rebind);
1068 if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
1069 return LDAP_NO_MEMORY;
1072 /* Setup timeout for the ldap_search_ext_s call - local and remote. */
1073 timeout.tv_sec = lp_ldap_timeout();
1074 timeout.tv_usec = 0;
1076 /* Setup alarm timeout.... Do we need both of these ? JRA.
1077 * Yes, I think we do need both of these. The server timeout only
1078 * covers the case where the server's operation takes too long. It
1079 * does not cover the case where the request hangs on its way to the
1080 * server. The server side timeout is not strictly necessary, it's
1081 * just a bit more kind to the server. VL. */
1084 CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
1085 alarm(lp_ldap_timeout());
1086 /* End setup timeout. */
1088 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1089 rc = ldap_search_ext_s(ldap_state->ldap_struct, base, scope,
1091 CONST_DISCARD(char **, attrs),
1092 attrsonly, sctrls, cctrls, &timeout,
1095 SAFE_FREE(utf8_filter);
1097 /* Teardown timeout. */
1098 CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
1102 return LDAP_TIMELIMIT_EXCEEDED;
1107 int smbldap_search(struct smbldap_state *ldap_state,
1108 const char *base, int scope, const char *filter,
1109 const char *attrs[], int attrsonly,
1112 return smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1113 attrsonly, NULL, NULL, LDAP_NO_LIMIT, res);
1116 int smbldap_search_paged(struct smbldap_state *ldap_state,
1117 const char *base, int scope, const char *filter,
1118 const char **attrs, int attrsonly, int pagesize,
1119 LDAPMessage **res, void **cookie)
1122 LDAPControl **rcontrols;
1123 LDAPControl *controls[2] = { NULL, NULL};
1124 BerElement *cookie_be = NULL;
1125 struct berval *cookie_bv = NULL;
1127 BOOL critical = True;
1131 DEBUG(3,("smbldap_search_paged: base => [%s], filter => [%s],"
1132 "scope => [%d], pagesize => [%d]\n",
1133 base, filter, scope, pagesize));
1135 cookie_be = ber_alloc_t(LBER_USE_DER);
1136 if (cookie_be == NULL) {
1137 DEBUG(0,("smbldap_create_page_control: ber_alloc_t returns "
1139 return LDAP_NO_MEMORY;
1142 /* construct cookie */
1143 if (*cookie != NULL) {
1144 ber_printf(cookie_be, "{iO}", (ber_int_t) pagesize, *cookie);
1145 ber_bvfree(*cookie); /* don't need it from last time */
1148 ber_printf(cookie_be, "{io}", (ber_int_t) pagesize, "", 0);
1150 ber_flatten(cookie_be, &cookie_bv);
1152 pr.ldctl_oid = CONST_DISCARD(char *, ADS_PAGE_CTL_OID);
1153 pr.ldctl_iscritical = (char) critical;
1154 pr.ldctl_value.bv_len = cookie_bv->bv_len;
1155 pr.ldctl_value.bv_val = cookie_bv->bv_val;
1160 rc = smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1161 0, controls, NULL, LDAP_NO_LIMIT, res);
1163 ber_free(cookie_be, 1);
1164 ber_bvfree(cookie_bv);
1167 DEBUG(3,("smbldap_search_paged: smbldap_search_ext(%s) "
1168 "failed with [%s]\n", filter, ldap_err2string(rc)));
1172 DEBUG(3,("smbldap_search_paged: search was successfull\n"));
1174 rc = ldap_parse_result(ldap_state->ldap_struct, *res, NULL, NULL,
1175 NULL, NULL, &rcontrols, 0);
1177 DEBUG(3,("smbldap_search_paged: ldap_parse_result failed " \
1178 "with [%s]\n", ldap_err2string(rc)));
1182 if (rcontrols == NULL)
1185 for (i=0; rcontrols[i]; i++) {
1187 if (strcmp(ADS_PAGE_CTL_OID, rcontrols[i]->ldctl_oid) != 0)
1190 cookie_be = ber_init(&rcontrols[i]->ldctl_value);
1191 ber_scanf(cookie_be,"{iO}", &tmp, &cookie_bv);
1192 /* the berval is the cookie, but must be freed when it is all
1194 if (cookie_bv->bv_len)
1195 *cookie=ber_bvdup(cookie_bv);
1198 ber_bvfree(cookie_bv);
1199 ber_free(cookie_be, 1);
1202 ldap_controls_free(rcontrols);
1207 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1209 int rc = LDAP_SERVER_DOWN;
1212 time_t endtime = time(NULL)+lp_ldap_timeout();
1214 SMB_ASSERT(ldap_state);
1216 DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1218 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1219 return LDAP_NO_MEMORY;
1222 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1223 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1229 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1231 int rc = LDAP_SERVER_DOWN;
1234 time_t endtime = time(NULL)+lp_ldap_timeout();
1236 SMB_ASSERT(ldap_state);
1238 DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1240 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1241 return LDAP_NO_MEMORY;
1244 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1245 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1251 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1253 int rc = LDAP_SERVER_DOWN;
1256 time_t endtime = time(NULL)+lp_ldap_timeout();
1258 SMB_ASSERT(ldap_state);
1260 DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1262 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1263 return LDAP_NO_MEMORY;
1266 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1267 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1273 int smbldap_extended_operation(struct smbldap_state *ldap_state,
1274 LDAP_CONST char *reqoid, struct berval *reqdata,
1275 LDAPControl **serverctrls, LDAPControl **clientctrls,
1276 char **retoidp, struct berval **retdatap)
1278 int rc = LDAP_SERVER_DOWN;
1280 time_t endtime = time(NULL)+lp_ldap_timeout();
1285 while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1286 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid,
1287 reqdata, serverctrls,
1288 clientctrls, retoidp, retdatap);
1292 /*******************************************************************
1293 run the search by name.
1294 ******************************************************************/
1295 int smbldap_search_suffix (struct smbldap_state *ldap_state, const char *filter,
1296 const char **search_attr, LDAPMessage ** result)
1298 int scope = LDAP_SCOPE_SUBTREE;
1301 rc = smbldap_search(ldap_state, lp_ldap_suffix(), scope, filter, search_attr, 0, result);
1303 if (rc != LDAP_SUCCESS) {
1304 char *ld_error = NULL;
1305 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1307 DEBUG(0,("smbldap_search_suffix: Problem during the LDAP search: %s (%s)\n",
1308 ld_error?ld_error:"(unknown)", ldap_err2string (rc)));
1309 SAFE_FREE(ld_error);
1315 static void smbldap_idle_fn(void **data, time_t *interval, time_t now)
1317 struct smbldap_state *state = (struct smbldap_state *)(*data);
1319 if (state->ldap_struct == NULL) {
1320 DEBUG(10,("ldap connection not connected...\n"));
1324 if ((state->last_use+SMBLDAP_IDLE_TIME) > now) {
1325 DEBUG(10,("ldap connection not idle...\n"));
1329 DEBUG(7,("ldap connection idle...closing connection\n"));
1330 smbldap_close(state);
1333 /**********************************************************************
1335 *********************************************************************/
1337 void smbldap_free_struct(struct smbldap_state **ldap_state)
1339 smbldap_close(*ldap_state);
1341 if ((*ldap_state)->bind_secret) {
1342 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1345 SAFE_FREE((*ldap_state)->bind_dn);
1346 SAFE_FREE((*ldap_state)->bind_secret);
1348 smb_unregister_idle_event((*ldap_state)->event_id);
1352 /* No need to free any further, as it is talloc()ed */
1356 /**********************************************************************
1357 Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1358 *********************************************************************/
1360 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state)
1362 *smbldap_state = TALLOC_ZERO_P(mem_ctx, struct smbldap_state);
1363 if (!*smbldap_state) {
1364 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1365 return NT_STATUS_NO_MEMORY;
1369 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1371 (*smbldap_state)->uri = "ldap://localhost";
1374 (*smbldap_state)->event_id =
1375 smb_register_idle_event(smbldap_idle_fn, (void *)(*smbldap_state),
1378 if ((*smbldap_state)->event_id == SMB_EVENT_ID_INVALID) {
1379 DEBUG(0,("Failed to register LDAP idle event!\n"));
1380 return NT_STATUS_INVALID_HANDLE;
1383 return NT_STATUS_OK;
1386 /**********************************************************************
1387 Add the sambaDomain to LDAP, so we don't have to search for this stuff
1388 again. This is a once-add operation for now.
1390 TODO: Add other attributes, and allow modification.
1391 *********************************************************************/
1392 static NTSTATUS add_new_domain_info(struct smbldap_state *ldap_state,
1393 const char *domain_name)
1396 fstring algorithmic_rid_base_string;
1398 LDAPMod **mods = NULL;
1401 LDAPMessage *result = NULL;
1403 const char **attr_list;
1404 uid_t u_low, u_high;
1405 gid_t g_low, g_high;
1406 uint32 rid_low, rid_high;
1408 slprintf (filter, sizeof (filter) - 1, "(&(%s=%s)(objectclass=%s))",
1409 get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN),
1410 domain_name, LDAP_OBJ_DOMINFO);
1412 attr_list = get_attr_list( dominfo_attr_list );
1413 rc = smbldap_search_suffix(ldap_state, filter, attr_list, &result);
1414 free_attr_list( attr_list );
1416 if (rc != LDAP_SUCCESS) {
1417 return NT_STATUS_UNSUCCESSFUL;
1420 num_result = ldap_count_entries(ldap_state->ldap_struct, result);
1422 if (num_result > 1) {
1423 DEBUG (0, ("More than domain with that name exists: bailing out!\n"));
1424 ldap_msgfree(result);
1425 return NT_STATUS_UNSUCCESSFUL;
1428 /* Check if we need to add an entry */
1429 DEBUG(3,("Adding new domain\n"));
1430 ldap_op = LDAP_MOD_ADD;
1432 pstr_sprintf(dn, "%s=%s,%s", get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN),
1433 domain_name, lp_ldap_suffix());
1435 /* Free original search */
1436 ldap_msgfree(result);
1438 /* make the changes - the entry *must* not already have samba attributes */
1439 smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN),
1442 /* If we don't have an entry, then ask secrets.tdb for what it thinks.
1443 It may choose to make it up */
1445 sid_to_string(sid_string, get_global_sam_sid());
1446 smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOM_SID), sid_string);
1448 slprintf(algorithmic_rid_base_string, sizeof(algorithmic_rid_base_string) - 1, "%i", algorithmic_rid_base());
1449 smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_ALGORITHMIC_RID_BASE),
1450 algorithmic_rid_base_string);
1451 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_DOMINFO);
1453 /* add the sambaNext[User|Group]Rid attributes if the idmap ranges are set.
1454 TODO: fix all the places where the line between idmap and normal operations
1455 needed by smbd gets fuzzy --jerry 2003-08-11 */
1457 if ( lp_idmap_uid(&u_low, &u_high) && lp_idmap_gid(&g_low, &g_high)
1458 && get_free_rid_range(&rid_low, &rid_high) )
1462 fstr_sprintf( rid_str, "%i", rid_high|USER_RID_TYPE );
1463 DEBUG(10,("setting next available user rid [%s]\n", rid_str));
1464 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1465 get_attr_key2string(dominfo_attr_list, LDAP_ATTR_NEXT_USERRID),
1468 fstr_sprintf( rid_str, "%i", rid_high|GROUP_RID_TYPE );
1469 DEBUG(10,("setting next available group rid [%s]\n", rid_str));
1470 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1471 get_attr_key2string(dominfo_attr_list, LDAP_ATTR_NEXT_GROUPRID),
1480 rc = smbldap_add(ldap_state, dn, mods);
1482 case LDAP_MOD_REPLACE:
1483 rc = smbldap_modify(ldap_state, dn, mods);
1486 DEBUG(0,("Wrong LDAP operation type: %d!\n", ldap_op));
1487 return NT_STATUS_INVALID_PARAMETER;
1490 if (rc!=LDAP_SUCCESS) {
1491 char *ld_error = NULL;
1492 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
1493 DEBUG(1,("failed to %s domain dn= %s with: %s\n\t%s\n",
1494 ldap_op == LDAP_MOD_ADD ? "add" : "modify",
1495 dn, ldap_err2string(rc),
1496 ld_error?ld_error:"unknown"));
1497 SAFE_FREE(ld_error);
1499 ldap_mods_free(mods, True);
1500 return NT_STATUS_UNSUCCESSFUL;
1503 DEBUG(2,("added: domain = %s in the LDAP database\n", domain_name));
1504 ldap_mods_free(mods, True);
1505 return NT_STATUS_OK;
1508 /**********************************************************************
1509 Search for the domain info entry
1510 *********************************************************************/
1511 NTSTATUS smbldap_search_domain_info(struct smbldap_state *ldap_state,
1512 LDAPMessage ** result, const char *domain_name,
1515 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1518 const char **attr_list;
1521 pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
1523 get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN),
1526 DEBUG(2, ("Searching for:[%s]\n", filter));
1529 attr_list = get_attr_list( dominfo_attr_list );
1530 rc = smbldap_search_suffix(ldap_state, filter, attr_list , result);
1531 free_attr_list( attr_list );
1533 if (rc != LDAP_SUCCESS) {
1534 DEBUG(2,("Problem during LDAPsearch: %s\n", ldap_err2string (rc)));
1535 DEBUG(2,("Query was: %s, %s\n", lp_ldap_suffix(), filter));
1536 } else if (ldap_count_entries(ldap_state->ldap_struct, *result) < 1) {
1537 DEBUG(3, ("Got no domain info entries for domain\n"));
1538 ldap_msgfree(*result);
1540 if (try_add && NT_STATUS_IS_OK(ret = add_new_domain_info(ldap_state, domain_name))) {
1541 return smbldap_search_domain_info(ldap_state, result, domain_name, False);
1544 DEBUG(0, ("Adding domain info for %s failed with %s\n",
1545 domain_name, nt_errstr(ret)));
1548 } else if ((count = ldap_count_entries(ldap_state->ldap_struct, *result)) > 1) {
1549 DEBUG(0, ("Got too many (%d) domain info entries for domain %s\n",
1550 count, domain_name));
1551 ldap_msgfree(*result);
1555 return NT_STATUS_OK;
1561 /*******************************************************************
1562 Return a copy of the DN for a LDAPMessage. Convert from utf8 to CH_UNIX.
1563 ********************************************************************/
1565 char *smbldap_get_dn(LDAP *ld, LDAPMessage *entry)
1567 char *utf8_dn, *unix_dn;
1569 utf8_dn = ldap_get_dn(ld, entry);
1571 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1574 if (pull_utf8_allocate(&unix_dn, utf8_dn) == (size_t)-1) {
1575 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 [%s]\n", utf8_dn));
1578 ldap_memfree(utf8_dn);
1582 /*******************************************************************
1583 Check if root-dse has a certain Control or Extension
1584 ********************************************************************/
1586 static BOOL smbldap_check_root_dse(struct smbldap_state *ldap_state, const char **attrs, const char *value)
1588 LDAPMessage *msg = NULL;
1589 LDAPMessage *entry = NULL;
1590 char **values = NULL;
1591 int rc, num_result, num_values, i;
1592 BOOL result = False;
1595 DEBUG(3,("smbldap_check_root_dse: nothing to look for\n"));
1599 if (!strequal(attrs[0], "supportedExtension") &&
1600 !strequal(attrs[0], "supportedControl")) {
1601 DEBUG(3,("smbldap_check_root_dse: no idea what to query root-dse for: %s ?\n", attrs[0]));
1605 rc = ldap_search_s(ldap_state->ldap_struct, "", LDAP_SCOPE_BASE,
1606 "(objectclass=*)", CONST_DISCARD(char **, attrs),
1609 if (rc != LDAP_SUCCESS) {
1610 DEBUG(3,("smbldap_check_root_dse: Could not search rootDSE\n"));
1614 num_result = ldap_count_entries(ldap_state->ldap_struct, msg);
1616 if (num_result != 1) {
1617 DEBUG(3,("smbldap_check_root_dse: Expected one rootDSE, got %d\n", num_result));
1621 entry = ldap_first_entry(ldap_state->ldap_struct, msg);
1623 if (entry == NULL) {
1624 DEBUG(3,("smbldap_check_root_dse: Could not retrieve rootDSE\n"));
1628 values = ldap_get_values(ldap_state->ldap_struct, entry, attrs[0]);
1630 if (values == NULL) {
1631 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not support any %s\n", attrs[0]));
1635 num_values = ldap_count_values(values);
1637 if (num_values == 0) {
1638 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not have any %s\n", attrs[0]));
1642 for (i=0; i<num_values; i++) {
1643 if (strcmp(values[i], value) == 0)
1650 ldap_value_free(values);
1657 /*******************************************************************
1658 Check if LDAP-Server supports a certain Control (OID in string format)
1659 ********************************************************************/
1661 BOOL smbldap_has_control(struct smbldap_state *ldap_state, const char *control)
1663 const char *attrs[] = { "supportedControl", NULL };
1664 return smbldap_check_root_dse(ldap_state, attrs, control);
1667 /*******************************************************************
1668 Check if LDAP-Server supports a certain Extension (OID in string format)
1669 ********************************************************************/
1671 BOOL smbldap_has_extension(struct smbldap_state *ldap_state, const char *extension)
1673 const char *attrs[] = { "supportedExtension", NULL };
1674 return smbldap_check_root_dse(ldap_state, attrs, extension);