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