source: trunk/samba-3.0.25pre1/source/lib/smbldap.c@ 1

Last change on this file since 1 was 1, checked in by Paul Smedley, 18 years ago

Initial code import

File size: 49.7 KB
Line 
1/*
2 Unix SMB/CIFS implementation.
3 LDAP protocol helper functions for SAMBA
4 Copyright (C) Jean François Micouleau 1998
5 Copyright (C) Gerald Carter 2001-2003
6 Copyright (C) Shahms King 2001
7 Copyright (C) Andrew Bartlett 2002-2003
8 Copyright (C) Stefan (metze) Metzmacher 2002-2003
9
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.
14
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.
19
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.
23
24*/
25
26#include "includes.h"
27#include "smbldap.h"
28
29#ifndef LDAP_OPT_SUCCESS
30#define LDAP_OPT_SUCCESS 0
31#endif
32
33/* Try not to hit the up or down server forever */
34
35#define SMBLDAP_DONT_PING_TIME 10 /* ping only all 10 seconds */
36#define SMBLDAP_NUM_RETRIES 8 /* retry only 8 times */
37
38#define SMBLDAP_IDLE_TIME 150 /* After 2.5 minutes disconnect */
39
40
41/* attributes used by Samba 2.2 */
42
43ATTRIB_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_SN, "sn" },
56 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
57 { LDAP_ATTR_HOME_PATH, "smbHome" },
58 { LDAP_ATTR_HOME_DRIVE, "homeDrive" },
59 { LDAP_ATTR_LOGON_SCRIPT, "scriptPath" },
60 { LDAP_ATTR_PROFILE_PATH, "profilePath" },
61 { LDAP_ATTR_DESC, "description" },
62 { LDAP_ATTR_USER_WKS, "userWorkstations"},
63 { LDAP_ATTR_USER_RID, "rid" },
64 { LDAP_ATTR_PRIMARY_GROUP_RID, "primaryGroupID"},
65 { LDAP_ATTR_LMPW, "lmPassword" },
66 { LDAP_ATTR_NTPW, "ntPassword" },
67 { LDAP_ATTR_DOMAIN, "domain" },
68 { LDAP_ATTR_OBJCLASS, "objectClass" },
69 { LDAP_ATTR_ACB_INFO, "acctFlags" },
70 { LDAP_ATTR_MOD_TIMESTAMP, "modifyTimestamp" },
71 { LDAP_ATTR_LIST_END, NULL }
72};
73
74ATTRIB_MAP_ENTRY attrib_map_to_delete_v22[] = {
75 { LDAP_ATTR_PWD_LAST_SET, "pwdLastSet" },
76 { LDAP_ATTR_PWD_CAN_CHANGE, "pwdCanChange" },
77 { LDAP_ATTR_PWD_MUST_CHANGE, "pwdMustChange" },
78 { LDAP_ATTR_LOGON_TIME, "logonTime" },
79 { LDAP_ATTR_LOGOFF_TIME, "logoffTime" },
80 { LDAP_ATTR_KICKOFF_TIME, "kickoffTime" },
81 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
82 { LDAP_ATTR_HOME_PATH, "smbHome" },
83 { LDAP_ATTR_HOME_DRIVE, "homeDrives" },
84 { LDAP_ATTR_LOGON_SCRIPT, "scriptPath" },
85 { LDAP_ATTR_PROFILE_PATH, "profilePath" },
86 { LDAP_ATTR_USER_WKS, "userWorkstations"},
87 { LDAP_ATTR_USER_RID, "rid" },
88 { LDAP_ATTR_PRIMARY_GROUP_RID, "primaryGroupID"},
89 { LDAP_ATTR_LMPW, "lmPassword" },
90 { LDAP_ATTR_NTPW, "ntPassword" },
91 { LDAP_ATTR_DOMAIN, "domain" },
92 { LDAP_ATTR_ACB_INFO, "acctFlags" },
93 { LDAP_ATTR_LIST_END, NULL }
94};
95
96/* attributes used by Samba 3.0's sambaSamAccount */
97
98ATTRIB_MAP_ENTRY attrib_map_v30[] = {
99 { LDAP_ATTR_UID, "uid" },
100 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
101 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
102 { LDAP_ATTR_UNIX_HOME, "homeDirectory" },
103 { LDAP_ATTR_PWD_LAST_SET, "sambaPwdLastSet" },
104 { LDAP_ATTR_PWD_CAN_CHANGE, "sambaPwdCanChange" },
105 { LDAP_ATTR_PWD_MUST_CHANGE, "sambaPwdMustChange" },
106 { LDAP_ATTR_LOGON_TIME, "sambaLogonTime" },
107 { LDAP_ATTR_LOGOFF_TIME, "sambaLogoffTime" },
108 { LDAP_ATTR_KICKOFF_TIME, "sambaKickoffTime" },
109 { LDAP_ATTR_CN, "cn" },
110 { LDAP_ATTR_SN, "sn" },
111 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
112 { LDAP_ATTR_HOME_DRIVE, "sambaHomeDrive" },
113 { LDAP_ATTR_HOME_PATH, "sambaHomePath" },
114 { LDAP_ATTR_LOGON_SCRIPT, "sambaLogonScript" },
115 { LDAP_ATTR_PROFILE_PATH, "sambaProfilePath" },
116 { LDAP_ATTR_DESC, "description" },
117 { LDAP_ATTR_USER_WKS, "sambaUserWorkstations" },
118 { LDAP_ATTR_USER_SID, LDAP_ATTRIBUTE_SID },
119 { LDAP_ATTR_PRIMARY_GROUP_SID, "sambaPrimaryGroupSID" },
120 { LDAP_ATTR_LMPW, "sambaLMPassword" },
121 { LDAP_ATTR_NTPW, "sambaNTPassword" },
122 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
123 { LDAP_ATTR_OBJCLASS, "objectClass" },
124 { LDAP_ATTR_ACB_INFO, "sambaAcctFlags" },
125 { LDAP_ATTR_MUNGED_DIAL, "sambaMungedDial" },
126 { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
127 { LDAP_ATTR_BAD_PASSWORD_TIME, "sambaBadPasswordTime" },
128 { LDAP_ATTR_PWD_HISTORY, "sambaPasswordHistory" },
129 { LDAP_ATTR_MOD_TIMESTAMP, "modifyTimestamp" },
130 { LDAP_ATTR_LOGON_HOURS, "sambaLogonHours" },
131 { LDAP_ATTR_LIST_END, NULL }
132};
133
134ATTRIB_MAP_ENTRY attrib_map_to_delete_v30[] = {
135 { LDAP_ATTR_PWD_LAST_SET, "sambaPwdLastSet" },
136 { LDAP_ATTR_PWD_CAN_CHANGE, "sambaPwdCanChange" },
137 { LDAP_ATTR_PWD_MUST_CHANGE, "sambaPwdMustChange" },
138 { LDAP_ATTR_LOGON_TIME, "sambaLogonTime" },
139 { LDAP_ATTR_LOGOFF_TIME, "sambaLogoffTime" },
140 { LDAP_ATTR_KICKOFF_TIME, "sambaKickoffTime" },
141 { LDAP_ATTR_HOME_DRIVE, "sambaHomeDrive" },
142 { LDAP_ATTR_HOME_PATH, "sambaHomePath" },
143 { LDAP_ATTR_LOGON_SCRIPT, "sambaLogonScript" },
144 { LDAP_ATTR_PROFILE_PATH, "sambaProfilePath" },
145 { LDAP_ATTR_USER_WKS, "sambaUserWorkstations" },
146 { LDAP_ATTR_USER_SID, LDAP_ATTRIBUTE_SID },
147 { LDAP_ATTR_PRIMARY_GROUP_SID, "sambaPrimaryGroupSID" },
148 { LDAP_ATTR_LMPW, "sambaLMPassword" },
149 { LDAP_ATTR_NTPW, "sambaNTPassword" },
150 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
151 { LDAP_ATTR_ACB_INFO, "sambaAcctFlags" },
152 { LDAP_ATTR_MUNGED_DIAL, "sambaMungedDial" },
153 { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
154 { LDAP_ATTR_BAD_PASSWORD_TIME, "sambaBadPasswordTime" },
155 { LDAP_ATTR_PWD_HISTORY, "sambaPasswordHistory" },
156 { LDAP_ATTR_LOGON_HOURS, "sambaLogonHours" },
157 { LDAP_ATTR_LIST_END, NULL }
158};
159
160/* attributes used for allocating RIDs */
161
162ATTRIB_MAP_ENTRY dominfo_attr_list[] = {
163 { LDAP_ATTR_DOMAIN, "sambaDomainName" },
164 { LDAP_ATTR_NEXT_RID, "sambaNextRid" },
165 { LDAP_ATTR_NEXT_USERRID, "sambaNextUserRid" },
166 { LDAP_ATTR_NEXT_GROUPRID, "sambaNextGroupRid" },
167 { LDAP_ATTR_DOM_SID, LDAP_ATTRIBUTE_SID },
168 { LDAP_ATTR_ALGORITHMIC_RID_BASE,"sambaAlgorithmicRidBase"},
169 { LDAP_ATTR_OBJCLASS, "objectClass" },
170 { LDAP_ATTR_LIST_END, NULL },
171};
172
173/* Samba 3.0 group mapping attributes */
174
175ATTRIB_MAP_ENTRY groupmap_attr_list[] = {
176 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
177 { LDAP_ATTR_GROUP_SID, LDAP_ATTRIBUTE_SID },
178 { LDAP_ATTR_GROUP_TYPE, "sambaGroupType" },
179 { LDAP_ATTR_SID_LIST, "sambaSIDList" },
180 { LDAP_ATTR_DESC, "description" },
181 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
182 { LDAP_ATTR_CN, "cn" },
183 { LDAP_ATTR_OBJCLASS, "objectClass" },
184 { LDAP_ATTR_LIST_END, NULL }
185};
186
187ATTRIB_MAP_ENTRY groupmap_attr_list_to_delete[] = {
188 { LDAP_ATTR_GROUP_SID, LDAP_ATTRIBUTE_SID },
189 { LDAP_ATTR_GROUP_TYPE, "sambaGroupType" },
190 { LDAP_ATTR_DESC, "description" },
191 { LDAP_ATTR_DISPLAY_NAME, "displayName" },
192 { LDAP_ATTR_SID_LIST, "sambaSIDList" },
193 { LDAP_ATTR_LIST_END, NULL }
194};
195
196/* idmap_ldap sambaUnixIdPool */
197
198ATTRIB_MAP_ENTRY idpool_attr_list[] = {
199 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
200 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
201 { LDAP_ATTR_OBJCLASS, "objectClass" },
202 { LDAP_ATTR_LIST_END, NULL }
203};
204
205ATTRIB_MAP_ENTRY sidmap_attr_list[] = {
206 { LDAP_ATTR_SID, LDAP_ATTRIBUTE_SID },
207 { LDAP_ATTR_UIDNUMBER, LDAP_ATTRIBUTE_UIDNUMBER},
208 { LDAP_ATTR_GIDNUMBER, LDAP_ATTRIBUTE_GIDNUMBER},
209 { LDAP_ATTR_OBJCLASS, "objectClass" },
210 { LDAP_ATTR_LIST_END, NULL }
211};
212
213/**********************************************************************
214 perform a simple table lookup and return the attribute name
215 **********************************************************************/
216
217 const char* get_attr_key2string( ATTRIB_MAP_ENTRY table[], int key )
218{
219 int i = 0;
220
221 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
222 if ( table[i].attrib == key )
223 return table[i].name;
224 i++;
225 }
226
227 return NULL;
228}
229
230
231/**********************************************************************
232 Return the list of attribute names from a mapping table
233 **********************************************************************/
234
235 const char** get_attr_list( TALLOC_CTX *mem_ctx, ATTRIB_MAP_ENTRY table[] )
236{
237 const char **names;
238 int i = 0;
239
240 while ( table[i].attrib != LDAP_ATTR_LIST_END )
241 i++;
242 i++;
243
244 names = TALLOC_ARRAY( mem_ctx, const char*, i );
245 if ( !names ) {
246 DEBUG(0,("get_attr_list: out of memory\n"));
247 return NULL;
248 }
249
250 i = 0;
251 while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
252 names[i] = talloc_strdup( names, table[i].name );
253 i++;
254 }
255 names[i] = NULL;
256
257 return names;
258}
259
260/*******************************************************************
261 Search an attribute and return the first value found.
262******************************************************************/
263
264 BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
265 const char *attribute, char *value,
266 int max_len)
267{
268 char **values;
269
270 if ( !attribute )
271 return False;
272
273 value[0] = '\0';
274
275 if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
276 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
277
278 return False;
279 }
280
281 if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, max_len, False) == (size_t)-1) {
282 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n",
283 attribute, values[0]));
284 ldap_value_free(values);
285 return False;
286 }
287
288 ldap_value_free(values);
289#ifdef DEBUG_PASSWORDS
290 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
291#endif
292 return True;
293}
294
295 BOOL smbldap_get_single_pstring (LDAP * ldap_struct, LDAPMessage * entry,
296 const char *attribute, pstring value)
297{
298 return smbldap_get_single_attribute(ldap_struct, entry,
299 attribute, value,
300 sizeof(pstring));
301}
302
303 char * smbldap_talloc_single_attribute(LDAP *ldap_struct, LDAPMessage *entry,
304 const char *attribute,
305 TALLOC_CTX *mem_ctx)
306{
307 char **values;
308 char *result;
309
310 if (attribute == NULL) {
311 return NULL;
312 }
313
314 values = ldap_get_values(ldap_struct, entry, attribute);
315
316 if (values == NULL) {
317 DEBUG(10, ("attribute %s does not exist\n", attribute));
318 return NULL;
319 }
320
321 if (ldap_count_values(values) != 1) {
322 DEBUG(10, ("attribute %s has %d values, expected only one\n",
323 attribute, ldap_count_values(values)));
324 ldap_value_free(values);
325 return NULL;
326 }
327
328 if (pull_utf8_talloc(mem_ctx, &result, values[0]) == (size_t)-1) {
329 DEBUG(10, ("pull_utf8_talloc failed\n"));
330 ldap_value_free(values);
331 return NULL;
332 }
333
334 ldap_value_free(values);
335
336#ifdef DEBUG_PASSWORDS
337 DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n",
338 attribute, result));
339#endif
340 return result;
341}
342
343 static int ldapmsg_destructor(LDAPMessage **result) {
344 ldap_msgfree(*result);
345 return 0;
346}
347
348 void talloc_autofree_ldapmsg(TALLOC_CTX *mem_ctx, LDAPMessage *result)
349{
350 LDAPMessage **handle;
351
352 if (result == NULL) {
353 return;
354 }
355
356 handle = TALLOC_P(mem_ctx, LDAPMessage *);
357 SMB_ASSERT(handle != NULL);
358
359 *handle = result;
360 talloc_set_destructor(handle, ldapmsg_destructor);
361}
362
363 static int ldapmod_destructor(LDAPMod ***mod) {
364 ldap_mods_free(*mod, True);
365 return 0;
366}
367
368 void talloc_autofree_ldapmod(TALLOC_CTX *mem_ctx, LDAPMod **mod)
369{
370 LDAPMod ***handle;
371
372 if (mod == NULL) {
373 return;
374 }
375
376 handle = TALLOC_P(mem_ctx, LDAPMod **);
377 SMB_ASSERT(handle != NULL);
378
379 *handle = mod;
380 talloc_set_destructor(handle, ldapmod_destructor);
381}
382
383/************************************************************************
384 Routine to manage the LDAPMod structure array
385 manage memory used by the array, by each struct, and values
386 ***********************************************************************/
387
388 void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
389{
390 LDAPMod **mods;
391 int i;
392 int j;
393
394 mods = *modlist;
395
396 /* sanity checks on the mod values */
397
398 if (attribute == NULL || *attribute == '\0') {
399 return;
400 }
401
402#if 0 /* commented out after discussion with abartlet. Do not reenable.
403 left here so other do not re-add similar code --jerry */
404 if (value == NULL || *value == '\0')
405 return;
406#endif
407
408 if (mods == NULL) {
409 mods = SMB_MALLOC_P(LDAPMod *);
410 if (mods == NULL) {
411 smb_panic("smbldap_set_mod: out of memory!\n");
412 /* notreached. */
413 abort();
414 }
415 mods[0] = NULL;
416 }
417
418 for (i = 0; mods[i] != NULL; ++i) {
419 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
420 break;
421 }
422
423 if (mods[i] == NULL) {
424 mods = SMB_REALLOC_ARRAY (mods, LDAPMod *, i + 2);
425 if (mods == NULL) {
426 smb_panic("smbldap_set_mod: out of memory!\n");
427 /* notreached. */
428 abort();
429 }
430 mods[i] = SMB_MALLOC_P(LDAPMod);
431 if (mods[i] == NULL) {
432 smb_panic("smbldap_set_mod: out of memory!\n");
433 /* notreached. */
434 abort();
435 }
436 mods[i]->mod_op = modop;
437 mods[i]->mod_values = NULL;
438 mods[i]->mod_type = SMB_STRDUP(attribute);
439 mods[i + 1] = NULL;
440 }
441
442 if (value != NULL) {
443 char *utf8_value = NULL;
444
445 j = 0;
446 if (mods[i]->mod_values != NULL) {
447 for (; mods[i]->mod_values[j] != NULL; j++);
448 }
449 mods[i]->mod_values = SMB_REALLOC_ARRAY(mods[i]->mod_values, char *, j + 2);
450
451 if (mods[i]->mod_values == NULL) {
452 smb_panic("smbldap_set_mod: out of memory!\n");
453 /* notreached. */
454 abort();
455 }
456
457 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
458 smb_panic("smbldap_set_mod: String conversion failure!\n");
459 /* notreached. */
460 abort();
461 }
462
463 mods[i]->mod_values[j] = utf8_value;
464
465 mods[i]->mod_values[j + 1] = NULL;
466 }
467 *modlist = mods;
468}
469
470/**********************************************************************
471 Set attribute to newval in LDAP, regardless of what value the
472 attribute had in LDAP before.
473*********************************************************************/
474
475 void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
476 LDAPMod ***mods,
477 const char *attribute, const char *newval)
478{
479 char oldval[2048]; /* current largest allowed value is mungeddial */
480 BOOL existed;
481
482 if (attribute == NULL) {
483 /* This can actually happen for ldapsam_compat where we for
484 * example don't have a password history */
485 return;
486 }
487
488 if (existing != NULL) {
489 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval, sizeof(oldval));
490 } else {
491 existed = False;
492 *oldval = '\0';
493 }
494
495 /* all of our string attributes are case insensitive */
496
497 if (existed && newval && (StrCaseCmp(oldval, newval) == 0)) {
498
499 /* Believe it or not, but LDAP will deny a delete and
500 an add at the same time if the values are the
501 same... */
502 DEBUG(10,("smbldap_make_mod: attribute |%s| not changed.\n", attribute));
503 return;
504 }
505
506 if (existed) {
507 /* There has been no value before, so don't delete it.
508 * Here's a possible race: We might end up with
509 * duplicate attributes */
510 /* By deleting exactly the value we found in the entry this
511 * should be race-free in the sense that the LDAP-Server will
512 * deny the complete operation if somebody changed the
513 * attribute behind our back. */
514 /* This will also allow modifying single valued attributes
515 * in Novell NDS. In NDS you have to first remove attribute and then
516 * you could add new value */
517
518 DEBUG(10,("smbldap_make_mod: deleting attribute |%s| values |%s|\n", attribute, oldval));
519 smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, oldval);
520 }
521
522 /* Regardless of the real operation (add or modify)
523 we add the new value here. We rely on deleting
524 the old value, should it exist. */
525
526 if ((newval != NULL) && (strlen(newval) > 0)) {
527 DEBUG(10,("smbldap_make_mod: adding attribute |%s| value |%s|\n", attribute, newval));
528 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
529 }
530}
531
532/**********************************************************************
533 Some varients of the LDAP rebind code do not pass in the third 'arg'
534 pointer to a void*, so we try and work around it by assuming that the
535 value of the 'LDAP *' pointer is the same as the one we had passed in
536 **********************************************************************/
537
538struct smbldap_state_lookup {
539 LDAP *ld;
540 struct smbldap_state *smbldap_state;
541 struct smbldap_state_lookup *prev, *next;
542};
543
544static struct smbldap_state_lookup *smbldap_state_lookup_list;
545
546static struct smbldap_state *smbldap_find_state(LDAP *ld)
547{
548 struct smbldap_state_lookup *t;
549
550 for (t = smbldap_state_lookup_list; t; t = t->next) {
551 if (t->ld == ld) {
552 return t->smbldap_state;
553 }
554 }
555 return NULL;
556}
557
558static void smbldap_delete_state(struct smbldap_state *smbldap_state)
559{
560 struct smbldap_state_lookup *t;
561
562 for (t = smbldap_state_lookup_list; t; t = t->next) {
563 if (t->smbldap_state == smbldap_state) {
564 DLIST_REMOVE(smbldap_state_lookup_list, t);
565 SAFE_FREE(t);
566 return;
567 }
568 }
569}
570
571static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state)
572{
573 struct smbldap_state *tmp_ldap_state;
574 struct smbldap_state_lookup *t;
575
576 if ((tmp_ldap_state = smbldap_find_state(ld))) {
577 SMB_ASSERT(tmp_ldap_state == smbldap_state);
578 return;
579 }
580
581 t = SMB_XMALLOC_P(struct smbldap_state_lookup);
582 ZERO_STRUCTP(t);
583
584 DLIST_ADD_END(smbldap_state_lookup_list, t, struct smbldap_state_lookup *);
585 t->ld = ld;
586 t->smbldap_state = smbldap_state;
587}
588
589/********************************************************************
590 start TLS on an existing LDAP connection
591*******************************************************************/
592
593int smb_ldap_start_tls(LDAP *ldap_struct, int version)
594{
595 int rc;
596
597 if (lp_ldap_ssl() != LDAP_SSL_START_TLS) {
598 return LDAP_SUCCESS;
599 }
600
601#ifdef LDAP_OPT_X_TLS
602 if (version != LDAP_VERSION3) {
603 DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
604 return LDAP_OPERATIONS_ERROR;
605 }
606
607 if ((rc = ldap_start_tls_s (ldap_struct, NULL, NULL)) != LDAP_SUCCESS) {
608 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
609 ldap_err2string(rc)));
610 return rc;
611 }
612
613 DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
614 return LDAP_SUCCESS;
615#else
616 DEBUG(0,("StartTLS not supported by LDAP client libraries!\n"));
617 return LDAP_OPERATIONS_ERROR;
618#endif
619}
620
621/********************************************************************
622 setup a connection to the LDAP server based on a uri
623*******************************************************************/
624
625int smb_ldap_setup_conn(LDAP **ldap_struct, const char *uri)
626{
627 int rc;
628
629 DEBUG(10, ("smb_ldap_setup_connection: %s\n", uri));
630
631#ifdef HAVE_LDAP_INITIALIZE
632
633 rc = ldap_initialize(ldap_struct, uri);
634 if (rc) {
635 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
636 }
637
638 return rc;
639#else
640
641 /* Parse the string manually */
642
643 {
644 int port = 0;
645 fstring protocol;
646 fstring host;
647 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
648
649
650 /* skip leading "URL:" (if any) */
651 if ( strnequal( uri, "URL:", 4 ) ) {
652 uri += 4;
653 }
654
655 sscanf(uri, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
656
657 if (port == 0) {
658 if (strequal(protocol, "ldap")) {
659 port = LDAP_PORT;
660 } else if (strequal(protocol, "ldaps")) {
661 port = LDAPS_PORT;
662 } else {
663 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
664 }
665 }
666
667 if ((*ldap_struct = ldap_init(host, port)) == NULL) {
668 DEBUG(0, ("ldap_init failed !\n"));
669 return LDAP_OPERATIONS_ERROR;
670 }
671
672 if (strequal(protocol, "ldaps")) {
673#ifdef LDAP_OPT_X_TLS
674 int tls = LDAP_OPT_X_TLS_HARD;
675 if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
676 {
677 DEBUG(0, ("Failed to setup a TLS session\n"));
678 }
679
680 DEBUG(3,("LDAPS option set...!\n"));
681#else
682 DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
683 return LDAP_OPERATIONS_ERROR;
684#endif /* LDAP_OPT_X_TLS */
685 }
686
687 }
688#endif /* HAVE_LDAP_INITIALIZE */
689 return LDAP_SUCCESS;
690}
691
692/********************************************************************
693 try to upgrade to Version 3 LDAP if not already, in either case return current
694 version
695 *******************************************************************/
696
697int smb_ldap_upgrade_conn(LDAP *ldap_struct, int *new_version)
698{
699 int version;
700 int rc;
701
702 /* assume the worst */
703 *new_version = LDAP_VERSION2;
704
705 rc = ldap_get_option(ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
706 if (rc) {
707 return rc;
708 }
709
710 if (version == LDAP_VERSION3) {
711 *new_version = LDAP_VERSION3;
712 return LDAP_SUCCESS;
713 }
714
715 /* try upgrade */
716 version = LDAP_VERSION3;
717 rc = ldap_set_option (ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
718 if (rc) {
719 return rc;
720 }
721
722 *new_version = LDAP_VERSION3;
723 return LDAP_SUCCESS;
724}
725
726/*******************************************************************
727 open a connection to the ldap server (just until the bind)
728 ******************************************************************/
729
730int smb_ldap_setup_full_conn(LDAP **ldap_struct, const char *uri)
731{
732 int rc, version;
733
734 rc = smb_ldap_setup_conn(ldap_struct, uri);
735 if (rc) {
736 return rc;
737 }
738
739 rc = smb_ldap_upgrade_conn(*ldap_struct, &version);
740 if (rc) {
741 return rc;
742 }
743
744 rc = smb_ldap_start_tls(*ldap_struct, version);
745 if (rc) {
746 return rc;
747 }
748
749 return LDAP_SUCCESS;
750}
751
752/*******************************************************************
753 open a connection to the ldap server.
754******************************************************************/
755static int smbldap_open_connection (struct smbldap_state *ldap_state)
756
757{
758 int rc = LDAP_SUCCESS;
759 int version;
760 LDAP **ldap_struct = &ldap_state->ldap_struct;
761
762 rc = smb_ldap_setup_conn(ldap_struct, ldap_state->uri);
763 if (rc) {
764 return rc;
765 }
766
767 /* Store the LDAP pointer in a lookup list */
768
769 smbldap_store_state(*ldap_struct, ldap_state);
770
771 /* Upgrade to LDAPv3 if possible */
772
773 rc = smb_ldap_upgrade_conn(*ldap_struct, &version);
774 if (rc) {
775 return rc;
776 }
777
778 /* Start TLS if required */
779
780 rc = smb_ldap_start_tls(*ldap_struct, version);
781 if (rc) {
782 return rc;
783 }
784
785 DEBUG(2, ("smbldap_open_connection: connection opened\n"));
786 return rc;
787}
788
789/*******************************************************************
790 a rebind function for authenticated referrals
791 This version takes a void* that we can shove useful stuff in :-)
792******************************************************************/
793#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
794#else
795static int rebindproc_with_state (LDAP * ld, char **whop, char **credp,
796 int *methodp, int freeit, void *arg)
797{
798 struct smbldap_state *ldap_state = arg;
799
800 /** @TODO Should we be doing something to check what servers we rebind to?
801 Could we get a referral to a machine that we don't want to give our
802 username and password to? */
803
804 if (freeit) {
805 SAFE_FREE(*whop);
806 if (*credp) {
807 memset(*credp, '\0', strlen(*credp));
808 }
809 SAFE_FREE(*credp);
810 } else {
811 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n",
812 ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
813
814 if (ldap_state->anonymous) {
815 *whop = NULL;
816 *credp = NULL;
817 } else {
818 *whop = SMB_STRDUP(ldap_state->bind_dn);
819 if (!*whop) {
820 return LDAP_NO_MEMORY;
821 }
822 *credp = SMB_STRDUP(ldap_state->bind_secret);
823 if (!*credp) {
824 SAFE_FREE(*whop);
825 return LDAP_NO_MEMORY;
826 }
827 }
828 *methodp = LDAP_AUTH_SIMPLE;
829 }
830
831 GetTimeOfDay(&ldap_state->last_rebind);
832
833 return 0;
834}
835#endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
836
837/*******************************************************************
838 a rebind function for authenticated referrals
839 This version takes a void* that we can shove useful stuff in :-)
840 and actually does the connection.
841******************************************************************/
842#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
843static int rebindproc_connect_with_state (LDAP *ldap_struct,
844 LDAP_CONST char *url,
845 ber_tag_t request,
846 ber_int_t msgid, void *arg)
847{
848 struct smbldap_state *ldap_state =
849 (struct smbldap_state *)arg;
850 int rc;
851 int version;
852
853 DEBUG(5,("rebindproc_connect_with_state: Rebinding to %s as \"%s\"\n",
854 url, ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
855
856 /* call START_TLS again (ldaps:// is handled by the OpenLDAP library
857 * itself) before rebinding to another LDAP server to avoid to expose
858 * our credentials. At least *try* to secure the connection - Guenther */
859
860 smb_ldap_upgrade_conn(ldap_struct, &version);
861 smb_ldap_start_tls(ldap_struct, version);
862
863 /** @TODO Should we be doing something to check what servers we rebind to?
864 Could we get a referral to a machine that we don't want to give our
865 username and password to? */
866
867 rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
868
869 /* only set the last rebind timestamp when we did rebind after a
870 * non-read LDAP operation. That way we avoid the replication sleep
871 * after a simple redirected search operation - Guenther */
872
873 switch (request) {
874
875 case LDAP_REQ_MODIFY:
876 case LDAP_REQ_ADD:
877 case LDAP_REQ_DELETE:
878 case LDAP_REQ_MODDN:
879 case LDAP_REQ_EXTENDED:
880 DEBUG(10,("rebindproc_connect_with_state: "
881 "setting last_rebind timestamp "
882 "(req: 0x%02x)\n", (unsigned int)request));
883 GetTimeOfDay(&ldap_state->last_rebind);
884 break;
885 default:
886 ZERO_STRUCT(ldap_state->last_rebind);
887 break;
888 }
889
890 return rc;
891}
892#endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
893
894/*******************************************************************
895 Add a rebind function for authenticated referrals
896******************************************************************/
897#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
898#else
899# if LDAP_SET_REBIND_PROC_ARGS == 2
900static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
901 int *method, int freeit )
902{
903 struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
904
905 return rebindproc_with_state(ldap_struct, whop, credp,
906 method, freeit, ldap_state);
907
908}
909# endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
910#endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
911
912/*******************************************************************
913 a rebind function for authenticated referrals
914 this also does the connection, but no void*.
915******************************************************************/
916#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
917# if LDAP_SET_REBIND_PROC_ARGS == 2
918static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
919 ber_int_t msgid)
920{
921 struct smbldap_state *ldap_state = smbldap_find_state(ld);
922
923 return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid,
924 ldap_state);
925}
926# endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
927#endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
928
929/*******************************************************************
930 connect to the ldap server under system privilege.
931******************************************************************/
932static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
933{
934 int rc;
935 int version;
936
937 if (!ldap_state->anonymous && !ldap_state->bind_dn) {
938
939 /* get the default dn and password only if they are not set already */
940 if (!fetch_ldap_pw(&ldap_state->bind_dn, &ldap_state->bind_secret)) {
941 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
942 return LDAP_INVALID_CREDENTIALS;
943 }
944 }
945
946 /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite
947 (OpenLDAP) doesnt' seem to support it */
948
949 DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
950 ldap_state->uri, ldap_state->bind_dn));
951
952#ifdef HAVE_LDAP_SET_REBIND_PROC
953#if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
954# if LDAP_SET_REBIND_PROC_ARGS == 2
955 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect);
956# endif
957# if LDAP_SET_REBIND_PROC_ARGS == 3
958 ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);
959# endif
960#else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
961# if LDAP_SET_REBIND_PROC_ARGS == 2
962 ldap_set_rebind_proc(ldap_struct, &rebindproc);
963# endif
964# if LDAP_SET_REBIND_PROC_ARGS == 3
965 ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);
966# endif
967#endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
968#endif
969
970 rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
971
972 if (rc != LDAP_SUCCESS) {
973 char *ld_error = NULL;
974 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
975 &ld_error);
976 DEBUG(ldap_state->num_failures ? 2 : 0,
977 ("failed to bind to server %s with dn=\"%s\" Error: %s\n\t%s\n",
978 ldap_state->uri,
979 ldap_state->bind_dn ? ldap_state->bind_dn : "[Anonymous bind]",
980 ldap_err2string(rc),
981 ld_error ? ld_error : "(unknown)"));
982 SAFE_FREE(ld_error);
983 ldap_state->num_failures++;
984 return rc;
985 }
986
987 ldap_state->num_failures = 0;
988 ldap_state->paged_results = False;
989
990 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
991
992 if (smbldap_has_control(ldap_state->ldap_struct, ADS_PAGE_CTL_OID) && version == 3) {
993 ldap_state->paged_results = True;
994 }
995
996 DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
997 DEBUGADD(10, ("ldap_connect_system: LDAP server %s support paged results\n",
998 ldap_state->paged_results ? "does" : "does not"));
999 return rc;
1000}
1001
1002/**********************************************************************
1003 Connect to LDAP server (called before every ldap operation)
1004*********************************************************************/
1005static int smbldap_open(struct smbldap_state *ldap_state)
1006{
1007 int rc, opt_rc;
1008 BOOL reopen = False;
1009 SMB_ASSERT(ldap_state);
1010
1011#ifndef NO_LDAP_SECURITY
1012 if (geteuid() != 0) {
1013 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
1014 return LDAP_INSUFFICIENT_ACCESS;
1015 }
1016#endif
1017
1018 if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
1019
1020#ifdef HAVE_UNIXSOCKET
1021 struct sockaddr_un addr;
1022#else
1023 struct sockaddr addr;
1024#endif
1025 socklen_t len = sizeof(addr);
1026 int sd;
1027
1028 opt_rc = ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd);
1029 if (opt_rc == 0 && (getpeername(sd, (struct sockaddr *) &addr, &len)) < 0 )
1030 reopen = True;
1031
1032#ifdef HAVE_UNIXSOCKET
1033 if (opt_rc == 0 && addr.sun_family == AF_UNIX)
1034 reopen = True;
1035#endif
1036 if (reopen) {
1037 /* the other end has died. reopen. */
1038 ldap_unbind(ldap_state->ldap_struct);
1039 ldap_state->ldap_struct = NULL;
1040 ldap_state->last_ping = (time_t)0;
1041 } else {
1042 ldap_state->last_ping = time(NULL);
1043 }
1044 }
1045
1046 if (ldap_state->ldap_struct != NULL) {
1047 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
1048 return LDAP_SUCCESS;
1049 }
1050
1051 if ((rc = smbldap_open_connection(ldap_state))) {
1052 return rc;
1053 }
1054
1055 if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
1056 ldap_unbind(ldap_state->ldap_struct);
1057 ldap_state->ldap_struct = NULL;
1058 return rc;
1059 }
1060
1061
1062 ldap_state->last_ping = time(NULL);
1063 ldap_state->pid = sys_getpid();
1064 DEBUG(4,("The LDAP server is succesfully connected\n"));
1065
1066 return LDAP_SUCCESS;
1067}
1068
1069/**********************************************************************
1070Disconnect from LDAP server
1071*********************************************************************/
1072static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
1073{
1074 if (!ldap_state)
1075 return NT_STATUS_INVALID_PARAMETER;
1076
1077 if (ldap_state->ldap_struct != NULL) {
1078 ldap_unbind(ldap_state->ldap_struct);
1079 ldap_state->ldap_struct = NULL;
1080 }
1081
1082 smbldap_delete_state(ldap_state);
1083
1084 DEBUG(5,("The connection to the LDAP server was closed\n"));
1085 /* maybe free the results here --metze */
1086
1087 return NT_STATUS_OK;
1088}
1089
1090static BOOL got_alarm;
1091
1092static void (*old_handler)(int);
1093
1094static void gotalarm_sig(int dummy)
1095{
1096 got_alarm = True;
1097}
1098
1099static int another_ldap_try(struct smbldap_state *ldap_state, int *rc,
1100 int *attempts, time_t endtime)
1101{
1102 time_t now = time(NULL);
1103 int open_rc = LDAP_SERVER_DOWN;
1104
1105 if (*rc != LDAP_SERVER_DOWN)
1106 goto no_next;
1107
1108 if (now >= endtime) {
1109 smbldap_close(ldap_state);
1110 *rc = LDAP_TIMEOUT;
1111 goto no_next;
1112 }
1113
1114 if (*attempts == 0) {
1115 got_alarm = False;
1116 old_handler = CatchSignal(SIGALRM, gotalarm_sig);
1117 alarm(endtime - now);
1118
1119 if (ldap_state->pid != sys_getpid())
1120 smbldap_close(ldap_state);
1121 }
1122
1123 while (1) {
1124
1125 if (*attempts != 0)
1126 smb_msleep(1000);
1127
1128 *attempts += 1;
1129
1130 open_rc = smbldap_open(ldap_state);
1131
1132 if (open_rc == LDAP_SUCCESS) {
1133 ldap_state->last_use = now;
1134 return True;
1135 }
1136
1137 if (open_rc == LDAP_INSUFFICIENT_ACCESS) {
1138 /* The fact that we are non-root or any other
1139 * access-denied condition will not change in the next
1140 * round of trying */
1141 *rc = open_rc;
1142 break;
1143 }
1144
1145 if (got_alarm) {
1146 *rc = LDAP_TIMEOUT;
1147 break;
1148 }
1149
1150 if (open_rc != LDAP_SUCCESS) {
1151 DEBUG(1, ("Connection to LDAP server failed for the "
1152 "%d try!\n", *attempts));
1153 }
1154 }
1155
1156 no_next:
1157 CatchSignal(SIGALRM, old_handler);
1158 alarm(0);
1159 ldap_state->last_use = now;
1160 return False;
1161}
1162
1163/*********************************************************************
1164 ********************************************************************/
1165
1166static int smbldap_search_ext(struct smbldap_state *ldap_state,
1167 const char *base, int scope, const char *filter,
1168 const char *attrs[], int attrsonly,
1169 LDAPControl **sctrls, LDAPControl **cctrls,
1170 int sizelimit, LDAPMessage **res)
1171{
1172 int rc = LDAP_SERVER_DOWN;
1173 int attempts = 0;
1174 char *utf8_filter;
1175 time_t endtime = time(NULL)+lp_ldap_timeout();
1176 struct timeval timeout;
1177
1178 SMB_ASSERT(ldap_state);
1179
1180 DEBUG(5,("smbldap_search_ext: base => [%s], filter => [%s], "
1181 "scope => [%d]\n", base, filter, scope));
1182
1183 if (ldap_state->last_rebind.tv_sec > 0) {
1184 struct timeval tval;
1185 SMB_BIG_INT tdiff = 0;
1186 int sleep_time = 0;
1187
1188 ZERO_STRUCT(tval);
1189 GetTimeOfDay(&tval);
1190
1191 tdiff = usec_time_diff(&tval, &ldap_state->last_rebind);
1192 tdiff /= 1000; /* Convert to milliseconds. */
1193
1194 sleep_time = lp_ldap_replication_sleep()-(int)tdiff;
1195 sleep_time = MIN(sleep_time, MAX_LDAP_REPLICATION_SLEEP_TIME);
1196
1197 if (sleep_time > 0) {
1198 /* we wait for the LDAP replication */
1199 DEBUG(5,("smbldap_search_ext: waiting %d milliseconds "
1200 "for LDAP replication.\n",sleep_time));
1201 smb_msleep(sleep_time);
1202 DEBUG(5,("smbldap_search_ext: go on!\n"));
1203 }
1204 ZERO_STRUCT(ldap_state->last_rebind);
1205 }
1206
1207 if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
1208 return LDAP_NO_MEMORY;
1209 }
1210
1211 /* Setup timeout for the ldap_search_ext_s call - local and remote. */
1212 timeout.tv_sec = lp_ldap_timeout();
1213 timeout.tv_usec = 0;
1214
1215 /* Setup alarm timeout.... Do we need both of these ? JRA.
1216 * Yes, I think we do need both of these. The server timeout only
1217 * covers the case where the server's operation takes too long. It
1218 * does not cover the case where the request hangs on its way to the
1219 * server. The server side timeout is not strictly necessary, it's
1220 * just a bit more kind to the server. VL. */
1221
1222 got_alarm = 0;
1223 CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
1224 alarm(lp_ldap_timeout());
1225 /* End setup timeout. */
1226
1227 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1228 rc = ldap_search_ext_s(ldap_state->ldap_struct, base, scope,
1229 utf8_filter,
1230 CONST_DISCARD(char **, attrs),
1231 attrsonly, sctrls, cctrls, &timeout,
1232 sizelimit, res);
1233 if (rc != LDAP_SUCCESS) {
1234 char *ld_error = NULL;
1235 int ld_errno;
1236
1237 ldap_get_option(ldap_state->ldap_struct,
1238 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1239
1240 ldap_get_option(ldap_state->ldap_struct,
1241 LDAP_OPT_ERROR_STRING, &ld_error);
1242 DEBUG(10, ("Failed search for base: %s, error: %d (%s) "
1243 "(%s)\n", base, ld_errno,
1244 ldap_err2string(rc),
1245 ld_error ? ld_error : "unknown"));
1246 SAFE_FREE(ld_error);
1247
1248 if (ld_errno == LDAP_SERVER_DOWN) {
1249 ldap_unbind(ldap_state->ldap_struct);
1250 ldap_state->ldap_struct = NULL;
1251 }
1252 }
1253 }
1254
1255 SAFE_FREE(utf8_filter);
1256
1257 /* Teardown timeout. */
1258 CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
1259 alarm(0);
1260
1261 if (got_alarm != 0)
1262 return LDAP_TIMELIMIT_EXCEEDED;
1263
1264 return rc;
1265}
1266
1267int smbldap_search(struct smbldap_state *ldap_state,
1268 const char *base, int scope, const char *filter,
1269 const char *attrs[], int attrsonly,
1270 LDAPMessage **res)
1271{
1272 return smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1273 attrsonly, NULL, NULL, LDAP_NO_LIMIT, res);
1274}
1275
1276int smbldap_search_paged(struct smbldap_state *ldap_state,
1277 const char *base, int scope, const char *filter,
1278 const char **attrs, int attrsonly, int pagesize,
1279 LDAPMessage **res, void **cookie)
1280{
1281 LDAPControl pr;
1282 LDAPControl **rcontrols;
1283 LDAPControl *controls[2] = { NULL, NULL};
1284 BerElement *cookie_be = NULL;
1285 struct berval *cookie_bv = NULL;
1286 int tmp = 0, i, rc;
1287 BOOL critical = True;
1288
1289 *res = NULL;
1290
1291 DEBUG(3,("smbldap_search_paged: base => [%s], filter => [%s],"
1292 "scope => [%d], pagesize => [%d]\n",
1293 base, filter, scope, pagesize));
1294
1295 cookie_be = ber_alloc_t(LBER_USE_DER);
1296 if (cookie_be == NULL) {
1297 DEBUG(0,("smbldap_create_page_control: ber_alloc_t returns "
1298 "NULL\n"));
1299 return LDAP_NO_MEMORY;
1300 }
1301
1302 /* construct cookie */
1303 if (*cookie != NULL) {
1304 ber_printf(cookie_be, "{iO}", (ber_int_t) pagesize, *cookie);
1305 ber_bvfree((struct berval *)*cookie); /* don't need it from last time */
1306 *cookie = NULL;
1307 } else {
1308 ber_printf(cookie_be, "{io}", (ber_int_t) pagesize, "", 0);
1309 }
1310 ber_flatten(cookie_be, &cookie_bv);
1311
1312 pr.ldctl_oid = CONST_DISCARD(char *, ADS_PAGE_CTL_OID);
1313 pr.ldctl_iscritical = (char) critical;
1314 pr.ldctl_value.bv_len = cookie_bv->bv_len;
1315 pr.ldctl_value.bv_val = cookie_bv->bv_val;
1316
1317 controls[0] = &pr;
1318 controls[1] = NULL;
1319
1320 rc = smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1321 0, controls, NULL, LDAP_NO_LIMIT, res);
1322
1323 ber_free(cookie_be, 1);
1324 ber_bvfree(cookie_bv);
1325
1326 if (rc != 0) {
1327 DEBUG(3,("smbldap_search_paged: smbldap_search_ext(%s) "
1328 "failed with [%s]\n", filter, ldap_err2string(rc)));
1329 goto done;
1330 }
1331
1332 DEBUG(3,("smbldap_search_paged: search was successfull\n"));
1333
1334 rc = ldap_parse_result(ldap_state->ldap_struct, *res, NULL, NULL,
1335 NULL, NULL, &rcontrols, 0);
1336 if (rc != 0) {
1337 DEBUG(3,("smbldap_search_paged: ldap_parse_result failed " \
1338 "with [%s]\n", ldap_err2string(rc)));
1339 goto done;
1340 }
1341
1342 if (rcontrols == NULL)
1343 goto done;
1344
1345 for (i=0; rcontrols[i]; i++) {
1346
1347 if (strcmp(ADS_PAGE_CTL_OID, rcontrols[i]->ldctl_oid) != 0)
1348 continue;
1349
1350 cookie_be = ber_init(&rcontrols[i]->ldctl_value);
1351 ber_scanf(cookie_be,"{iO}", &tmp, &cookie_bv);
1352 /* the berval is the cookie, but must be freed when it is all
1353 done */
1354 if (cookie_bv->bv_len)
1355 *cookie=ber_bvdup(cookie_bv);
1356 else
1357 *cookie=NULL;
1358 ber_bvfree(cookie_bv);
1359 ber_free(cookie_be, 1);
1360 break;
1361 }
1362 ldap_controls_free(rcontrols);
1363done:
1364 return rc;
1365}
1366
1367int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1368{
1369 int rc = LDAP_SERVER_DOWN;
1370 int attempts = 0;
1371 char *utf8_dn;
1372 time_t endtime = time(NULL)+lp_ldap_timeout();
1373
1374 SMB_ASSERT(ldap_state);
1375
1376 DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1377
1378 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1379 return LDAP_NO_MEMORY;
1380 }
1381
1382 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1383 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1384 if (rc != LDAP_SUCCESS) {
1385 char *ld_error = NULL;
1386 int ld_errno;
1387
1388 ldap_get_option(ldap_state->ldap_struct,
1389 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1390
1391 ldap_get_option(ldap_state->ldap_struct,
1392 LDAP_OPT_ERROR_STRING, &ld_error);
1393 DEBUG(10, ("Failed to modify dn: %s, error: %d (%s) "
1394 "(%s)\n", dn, ld_errno,
1395 ldap_err2string(rc),
1396 ld_error ? ld_error : "unknown"));
1397 SAFE_FREE(ld_error);
1398
1399 if (ld_errno == LDAP_SERVER_DOWN) {
1400 ldap_unbind(ldap_state->ldap_struct);
1401 ldap_state->ldap_struct = NULL;
1402 }
1403 }
1404 }
1405
1406 SAFE_FREE(utf8_dn);
1407 return rc;
1408}
1409
1410int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1411{
1412 int rc = LDAP_SERVER_DOWN;
1413 int attempts = 0;
1414 char *utf8_dn;
1415 time_t endtime = time(NULL)+lp_ldap_timeout();
1416
1417 SMB_ASSERT(ldap_state);
1418
1419 DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1420
1421 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1422 return LDAP_NO_MEMORY;
1423 }
1424
1425 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1426 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1427 if (rc != LDAP_SUCCESS) {
1428 char *ld_error = NULL;
1429 int ld_errno;
1430
1431 ldap_get_option(ldap_state->ldap_struct,
1432 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1433
1434 ldap_get_option(ldap_state->ldap_struct,
1435 LDAP_OPT_ERROR_STRING, &ld_error);
1436 DEBUG(10, ("Failed to add dn: %s, error: %d (%s) "
1437 "(%s)\n", dn, ld_errno,
1438 ldap_err2string(rc),
1439 ld_error ? ld_error : "unknown"));
1440 SAFE_FREE(ld_error);
1441
1442 if (ld_errno == LDAP_SERVER_DOWN) {
1443 ldap_unbind(ldap_state->ldap_struct);
1444 ldap_state->ldap_struct = NULL;
1445 }
1446 }
1447 }
1448
1449 SAFE_FREE(utf8_dn);
1450 return rc;
1451}
1452
1453int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1454{
1455 int rc = LDAP_SERVER_DOWN;
1456 int attempts = 0;
1457 char *utf8_dn;
1458 time_t endtime = time(NULL)+lp_ldap_timeout();
1459
1460 SMB_ASSERT(ldap_state);
1461
1462 DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1463
1464 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1465 return LDAP_NO_MEMORY;
1466 }
1467
1468 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1469 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1470 if (rc != LDAP_SUCCESS) {
1471 char *ld_error = NULL;
1472 int ld_errno;
1473
1474 ldap_get_option(ldap_state->ldap_struct,
1475 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1476
1477 ldap_get_option(ldap_state->ldap_struct,
1478 LDAP_OPT_ERROR_STRING, &ld_error);
1479 DEBUG(10, ("Failed to delete dn: %s, error: %d (%s) "
1480 "(%s)\n", dn, ld_errno,
1481 ldap_err2string(rc),
1482 ld_error ? ld_error : "unknown"));
1483 SAFE_FREE(ld_error);
1484
1485 if (ld_errno == LDAP_SERVER_DOWN) {
1486 ldap_unbind(ldap_state->ldap_struct);
1487 ldap_state->ldap_struct = NULL;
1488 }
1489 }
1490 }
1491
1492 SAFE_FREE(utf8_dn);
1493 return rc;
1494}
1495
1496int smbldap_extended_operation(struct smbldap_state *ldap_state,
1497 LDAP_CONST char *reqoid, struct berval *reqdata,
1498 LDAPControl **serverctrls, LDAPControl **clientctrls,
1499 char **retoidp, struct berval **retdatap)
1500{
1501 int rc = LDAP_SERVER_DOWN;
1502 int attempts = 0;
1503 time_t endtime = time(NULL)+lp_ldap_timeout();
1504
1505 if (!ldap_state)
1506 return (-1);
1507
1508 while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1509 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid,
1510 reqdata, serverctrls,
1511 clientctrls, retoidp, retdatap);
1512 if (rc != LDAP_SUCCESS) {
1513 char *ld_error = NULL;
1514 int ld_errno;
1515
1516 ldap_get_option(ldap_state->ldap_struct,
1517 LDAP_OPT_ERROR_NUMBER, &ld_errno);
1518
1519 ldap_get_option(ldap_state->ldap_struct,
1520 LDAP_OPT_ERROR_STRING, &ld_error);
1521 DEBUG(10, ("Extended operation failed with error: "
1522 "%d (%s) (%s)\n", ld_errno,
1523 ldap_err2string(rc),
1524 ld_error ? ld_error : "unknown"));
1525 SAFE_FREE(ld_error);
1526
1527 if (ld_errno == LDAP_SERVER_DOWN) {
1528 ldap_unbind(ldap_state->ldap_struct);
1529 ldap_state->ldap_struct = NULL;
1530 }
1531 }
1532 }
1533
1534 return rc;
1535}
1536
1537/*******************************************************************
1538 run the search by name.
1539******************************************************************/
1540int smbldap_search_suffix (struct smbldap_state *ldap_state,
1541 const char *filter, const char **search_attr,
1542 LDAPMessage ** result)
1543{
1544 return smbldap_search(ldap_state, lp_ldap_suffix(), LDAP_SCOPE_SUBTREE,
1545 filter, search_attr, 0, result);
1546}
1547
1548static void smbldap_idle_fn(void **data, time_t *interval, time_t now)
1549{
1550 struct smbldap_state *state = (struct smbldap_state *)(*data);
1551
1552 if (state->ldap_struct == NULL) {
1553 DEBUG(10,("ldap connection not connected...\n"));
1554 return;
1555 }
1556
1557 if ((state->last_use+SMBLDAP_IDLE_TIME) > now) {
1558 DEBUG(10,("ldap connection not idle...\n"));
1559 return;
1560 }
1561
1562 DEBUG(7,("ldap connection idle...closing connection\n"));
1563 smbldap_close(state);
1564}
1565
1566/**********************************************************************
1567 Housekeeping
1568 *********************************************************************/
1569
1570void smbldap_free_struct(struct smbldap_state **ldap_state)
1571{
1572 smbldap_close(*ldap_state);
1573
1574 if ((*ldap_state)->bind_secret) {
1575 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1576 }
1577
1578 SAFE_FREE((*ldap_state)->bind_dn);
1579 SAFE_FREE((*ldap_state)->bind_secret);
1580
1581 smb_unregister_idle_event((*ldap_state)->event_id);
1582
1583 *ldap_state = NULL;
1584
1585 /* No need to free any further, as it is talloc()ed */
1586}
1587
1588
1589/**********************************************************************
1590 Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1591 *********************************************************************/
1592
1593NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state)
1594{
1595 *smbldap_state = TALLOC_ZERO_P(mem_ctx, struct smbldap_state);
1596 if (!*smbldap_state) {
1597 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1598 return NT_STATUS_NO_MEMORY;
1599 }
1600
1601 if (location) {
1602 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1603 } else {
1604 (*smbldap_state)->uri = "ldap://localhost";
1605 }
1606
1607 (*smbldap_state)->event_id =
1608 smb_register_idle_event(smbldap_idle_fn, (void *)(*smbldap_state),
1609 SMBLDAP_IDLE_TIME);
1610
1611 if ((*smbldap_state)->event_id == SMB_EVENT_ID_INVALID) {
1612 DEBUG(0,("Failed to register LDAP idle event!\n"));
1613 return NT_STATUS_INVALID_HANDLE;
1614 }
1615
1616 return NT_STATUS_OK;
1617}
1618
1619/*******************************************************************
1620 Return a copy of the DN for a LDAPMessage. Convert from utf8 to CH_UNIX.
1621********************************************************************/
1622char *smbldap_get_dn(LDAP *ld, LDAPMessage *entry)
1623{
1624 char *utf8_dn, *unix_dn;
1625
1626 utf8_dn = ldap_get_dn(ld, entry);
1627 if (!utf8_dn) {
1628 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1629 return NULL;
1630 }
1631 if (pull_utf8_allocate(&unix_dn, utf8_dn) == (size_t)-1) {
1632 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 [%s]\n", utf8_dn));
1633 return NULL;
1634 }
1635 ldap_memfree(utf8_dn);
1636 return unix_dn;
1637}
1638
1639 const char *smbldap_talloc_dn(TALLOC_CTX *mem_ctx, LDAP *ld,
1640 LDAPMessage *entry)
1641{
1642 char *utf8_dn, *unix_dn;
1643
1644 utf8_dn = ldap_get_dn(ld, entry);
1645 if (!utf8_dn) {
1646 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1647 return NULL;
1648 }
1649 if (pull_utf8_talloc(mem_ctx, &unix_dn, utf8_dn) == (size_t)-1) {
1650 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 "
1651 "[%s]\n", utf8_dn));
1652 return NULL;
1653 }
1654 ldap_memfree(utf8_dn);
1655 return unix_dn;
1656}
1657
1658/*******************************************************************
1659 Check if root-dse has a certain Control or Extension
1660********************************************************************/
1661
1662static BOOL smbldap_check_root_dse(LDAP *ld, const char **attrs, const char *value)
1663{
1664 LDAPMessage *msg = NULL;
1665 LDAPMessage *entry = NULL;
1666 char **values = NULL;
1667 int rc, num_result, num_values, i;
1668 BOOL result = False;
1669
1670 if (!attrs[0]) {
1671 DEBUG(3,("smbldap_check_root_dse: nothing to look for\n"));
1672 return False;
1673 }
1674
1675 if (!strequal(attrs[0], "supportedExtension") &&
1676 !strequal(attrs[0], "supportedControl") &&
1677 !strequal(attrs[0], "namingContexts")) {
1678 DEBUG(3,("smbldap_check_root_dse: no idea what to query root-dse for: %s ?\n", attrs[0]));
1679 return False;
1680 }
1681
1682 rc = ldap_search_s(ld, "", LDAP_SCOPE_BASE,
1683 "(objectclass=*)", CONST_DISCARD(char **, attrs), 0 , &msg);
1684
1685 if (rc != LDAP_SUCCESS) {
1686 DEBUG(3,("smbldap_check_root_dse: Could not search rootDSE\n"));
1687 return False;
1688 }
1689
1690 num_result = ldap_count_entries(ld, msg);
1691
1692 if (num_result != 1) {
1693 DEBUG(3,("smbldap_check_root_dse: Expected one rootDSE, got %d\n", num_result));
1694 goto done;
1695 }
1696
1697 entry = ldap_first_entry(ld, msg);
1698
1699 if (entry == NULL) {
1700 DEBUG(3,("smbldap_check_root_dse: Could not retrieve rootDSE\n"));
1701 goto done;
1702 }
1703
1704 values = ldap_get_values(ld, entry, attrs[0]);
1705
1706 if (values == NULL) {
1707 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not support any %s\n", attrs[0]));
1708 goto done;
1709 }
1710
1711 num_values = ldap_count_values(values);
1712
1713 if (num_values == 0) {
1714 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not have any %s\n", attrs[0]));
1715 goto done;
1716 }
1717
1718 for (i=0; i<num_values; i++) {
1719 if (strcmp(values[i], value) == 0)
1720 result = True;
1721 }
1722
1723
1724 done:
1725 if (values != NULL)
1726 ldap_value_free(values);
1727 if (msg != NULL)
1728 ldap_msgfree(msg);
1729
1730 return result;
1731
1732}
1733
1734/*******************************************************************
1735 Check if LDAP-Server supports a certain Control (OID in string format)
1736********************************************************************/
1737
1738BOOL smbldap_has_control(LDAP *ld, const char *control)
1739{
1740 const char *attrs[] = { "supportedControl", NULL };
1741 return smbldap_check_root_dse(ld, attrs, control);
1742}
1743
1744/*******************************************************************
1745 Check if LDAP-Server supports a certain Extension (OID in string format)
1746********************************************************************/
1747
1748BOOL smbldap_has_extension(LDAP *ld, const char *extension)
1749{
1750 const char *attrs[] = { "supportedExtension", NULL };
1751 return smbldap_check_root_dse(ld, attrs, extension);
1752}
1753
1754/*******************************************************************
1755 Check if LDAP-Server holds a given namingContext
1756********************************************************************/
1757
1758BOOL smbldap_has_naming_context(LDAP *ld, const char *naming_context)
1759{
1760 const char *attrs[] = { "namingContexts", NULL };
1761 return smbldap_check_root_dse(ld, attrs, naming_context);
1762}
1763
1764BOOL smbldap_set_creds(struct smbldap_state *ldap_state, BOOL anon, const char *dn, const char *secret)
1765{
1766 ldap_state->anonymous = anon;
1767
1768 /* free any previously set credential */
1769
1770 SAFE_FREE(ldap_state->bind_dn);
1771 if (ldap_state->bind_secret) {
1772 /* make sure secrets are zeroed out of memory */
1773 memset(ldap_state->bind_secret, '\0', strlen(ldap_state->bind_secret));
1774 SAFE_FREE(ldap_state->bind_secret);
1775 }
1776
1777 if ( ! anon) {
1778 ldap_state->bind_dn = SMB_STRDUP(dn);
1779 ldap_state->bind_secret = SMB_STRDUP(secret);
1780 }
1781
1782 return True;
1783}
Note: See TracBrowser for help on using the repository browser.