Fix warnings caused by double ";;" at the end of the time_mono() fixes.
[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         struct timespec ts;
962
963         /** @TODO Should we be doing something to check what servers we rebind to?
964             Could we get a referral to a machine that we don't want to give our
965             username and password to? */
966
967         if (freeit) {
968                 SAFE_FREE(*whop);
969                 if (*credp) {
970                         memset(*credp, '\0', strlen(*credp));
971                 }
972                 SAFE_FREE(*credp);
973         } else {
974                 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n", 
975                           ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
976
977                 if (ldap_state->anonymous) {
978                         *whop = NULL;
979                         *credp = NULL;
980                 } else {
981                         *whop = SMB_STRDUP(ldap_state->bind_dn);
982                         if (!*whop) {
983                                 return LDAP_NO_MEMORY;
984                         }
985                         *credp = SMB_STRDUP(ldap_state->bind_secret);
986                         if (!*credp) {
987                                 SAFE_FREE(*whop);
988                                 return LDAP_NO_MEMORY;
989                         }
990                 }
991                 *methodp = LDAP_AUTH_SIMPLE;
992         }
993
994         clock_gettime_mono(&ts);
995         ldap_state->last_rebind = convert_timespec_to_timeval(ts);
996
997         return 0;
998 }
999 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1000
1001 /*******************************************************************
1002  a rebind function for authenticated referrals
1003  This version takes a void* that we can shove useful stuff in :-)
1004  and actually does the connection.
1005 ******************************************************************/
1006 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1007 static int rebindproc_connect_with_state (LDAP *ldap_struct, 
1008                                           LDAP_CONST char *url, 
1009                                           ber_tag_t request,
1010                                           ber_int_t msgid, void *arg)
1011 {
1012         struct smbldap_state *ldap_state =
1013                 (struct smbldap_state *)arg;
1014         int rc;
1015         struct timespec ts;
1016         int version;
1017
1018         DEBUG(5,("rebindproc_connect_with_state: Rebinding to %s as \"%s\"\n", 
1019                  url, ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
1020
1021         /* call START_TLS again (ldaps:// is handled by the OpenLDAP library
1022          * itself) before rebinding to another LDAP server to avoid to expose
1023          * our credentials. At least *try* to secure the connection - Guenther */
1024
1025         smb_ldap_upgrade_conn(ldap_struct, &version);
1026         smb_ldap_start_tls(ldap_struct, version);
1027
1028         /** @TODO Should we be doing something to check what servers we rebind to?
1029             Could we get a referral to a machine that we don't want to give our
1030             username and password to? */
1031
1032         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
1033
1034         /* only set the last rebind timestamp when we did rebind after a
1035          * non-read LDAP operation. That way we avoid the replication sleep
1036          * after a simple redirected search operation - Guenther */
1037
1038         switch (request) {
1039
1040                 case LDAP_REQ_MODIFY:
1041                 case LDAP_REQ_ADD:
1042                 case LDAP_REQ_DELETE:
1043                 case LDAP_REQ_MODDN:
1044                 case LDAP_REQ_EXTENDED:
1045                         DEBUG(10,("rebindproc_connect_with_state: "
1046                                 "setting last_rebind timestamp "
1047                                 "(req: 0x%02x)\n", (unsigned int)request));
1048                         clock_gettime_mono(&ts);
1049                         ldap_state->last_rebind = convert_timespec_to_timeval(ts);
1050                         break;
1051                 default:
1052                         ZERO_STRUCT(ldap_state->last_rebind);
1053                         break;
1054         }
1055
1056         return rc;
1057 }
1058 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1059
1060 /*******************************************************************
1061  Add a rebind function for authenticated referrals
1062 ******************************************************************/
1063 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1064 #else
1065 # if LDAP_SET_REBIND_PROC_ARGS == 2
1066 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
1067                        int *method, int freeit )
1068 {
1069         struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
1070
1071         return rebindproc_with_state(ldap_struct, whop, credp,
1072                                      method, freeit, ldap_state);
1073 }
1074 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
1075 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1076
1077 /*******************************************************************
1078  a rebind function for authenticated referrals
1079  this also does the connection, but no void*.
1080 ******************************************************************/
1081 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1082 # if LDAP_SET_REBIND_PROC_ARGS == 2
1083 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
1084                                ber_int_t msgid)
1085 {
1086         struct smbldap_state *ldap_state = smbldap_find_state(ld);
1087
1088         return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid, 
1089                                              ldap_state);
1090 }
1091 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
1092 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1093
1094 /*******************************************************************
1095  connect to the ldap server under system privilege.
1096 ******************************************************************/
1097 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
1098 {
1099         int rc;
1100         int version;
1101
1102         if (!ldap_state->anonymous && !ldap_state->bind_dn) {
1103                 char *bind_dn = NULL;
1104                 char *bind_secret = NULL;
1105
1106                 /* get the default dn and password only if they are not set already */
1107                 if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
1108                         DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
1109                         return LDAP_INVALID_CREDENTIALS;
1110                 }
1111                 smbldap_set_creds(ldap_state, false, bind_dn, bind_secret);
1112                 SAFE_FREE(bind_dn);
1113                 memset(bind_secret, '\0', strlen(bind_secret));
1114                 SAFE_FREE(bind_secret);
1115         }
1116
1117         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
1118            (OpenLDAP) doesnt' seem to support it */
1119
1120         DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
1121                   ldap_state->uri, ldap_state->bind_dn));
1122
1123 #ifdef HAVE_LDAP_SET_REBIND_PROC
1124 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1125 # if LDAP_SET_REBIND_PROC_ARGS == 2     
1126         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect); 
1127 # endif
1128 # if LDAP_SET_REBIND_PROC_ARGS == 3     
1129         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);  
1130 # endif
1131 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1132 # if LDAP_SET_REBIND_PROC_ARGS == 2     
1133         ldap_set_rebind_proc(ldap_struct, &rebindproc); 
1134 # endif
1135 # if LDAP_SET_REBIND_PROC_ARGS == 3     
1136         ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);  
1137 # endif
1138 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1139 #endif
1140
1141         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
1142
1143         if (rc != LDAP_SUCCESS) {
1144                 char *ld_error = NULL;
1145                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1146                                 &ld_error);
1147                 DEBUG(ldap_state->num_failures ? 2 : 0,
1148                       ("failed to bind to server %s with dn=\"%s\" Error: %s\n\t%s\n",
1149                                ldap_state->uri,
1150                                ldap_state->bind_dn ? ldap_state->bind_dn : "[Anonymous bind]",
1151                                ldap_err2string(rc),
1152                                ld_error ? ld_error : "(unknown)"));
1153                 SAFE_FREE(ld_error);
1154                 ldap_state->num_failures++;
1155                 return rc;
1156         }
1157
1158         ldap_state->num_failures = 0;
1159         ldap_state->paged_results = False;
1160
1161         ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
1162
1163         if (smbldap_has_control(ldap_state->ldap_struct, ADS_PAGE_CTL_OID) && version == 3) {
1164                 ldap_state->paged_results = True;
1165         }
1166
1167         DEBUG(3, ("ldap_connect_system: successful connection to the LDAP server\n"));
1168         DEBUGADD(10, ("ldap_connect_system: LDAP server %s support paged results\n", 
1169                 ldap_state->paged_results ? "does" : "does not"));
1170         return rc;
1171 }
1172
1173 static void smbldap_idle_fn(struct event_context *event_ctx,
1174                             struct timed_event *te,
1175                             struct timeval now_abs,
1176                             void *private_data);
1177
1178 /**********************************************************************
1179  Connect to LDAP server (called before every ldap operation)
1180 *********************************************************************/
1181 static int smbldap_open(struct smbldap_state *ldap_state)
1182 {
1183         int rc, opt_rc;
1184         bool reopen = False;
1185         SMB_ASSERT(ldap_state);
1186
1187         if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time_mono(NULL))) {
1188
1189 #ifdef HAVE_UNIXSOCKET
1190                 struct sockaddr_un addr;
1191 #else
1192                 struct sockaddr addr;
1193 #endif
1194                 socklen_t len = sizeof(addr);
1195                 int sd;
1196
1197                 opt_rc = ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd);
1198                 if (opt_rc == 0 && (getpeername(sd, (struct sockaddr *) &addr, &len)) < 0 )
1199                         reopen = True;
1200
1201 #ifdef HAVE_UNIXSOCKET
1202                 if (opt_rc == 0 && addr.sun_family == AF_UNIX)
1203                         reopen = True;
1204 #endif
1205                 if (reopen) {
1206                         /* the other end has died. reopen. */
1207                         ldap_unbind(ldap_state->ldap_struct);
1208                         ldap_state->ldap_struct = NULL;
1209                         ldap_state->last_ping = (time_t)0;
1210                 } else {
1211                         ldap_state->last_ping = time_mono(NULL);
1212                 } 
1213         }
1214
1215         if (ldap_state->ldap_struct != NULL) {
1216                 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
1217                 return LDAP_SUCCESS;
1218         }
1219
1220         if ((rc = smbldap_open_connection(ldap_state))) {
1221                 return rc;
1222         }
1223
1224         if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
1225                 ldap_unbind(ldap_state->ldap_struct);
1226                 ldap_state->ldap_struct = NULL;
1227                 return rc;
1228         }
1229
1230
1231         ldap_state->last_ping = time_mono(NULL);
1232         ldap_state->pid = sys_getpid();
1233
1234         TALLOC_FREE(ldap_state->idle_event);
1235
1236         if (ldap_state->event_context != NULL) {
1237                 ldap_state->idle_event = event_add_timed(
1238                         ldap_state->event_context, NULL,
1239                         timeval_current_ofs(SMBLDAP_IDLE_TIME, 0),
1240                         smbldap_idle_fn, ldap_state);
1241         }
1242
1243         DEBUG(4,("The LDAP server is successfully connected\n"));
1244
1245         return LDAP_SUCCESS;
1246 }
1247
1248 /**********************************************************************
1249 Disconnect from LDAP server 
1250 *********************************************************************/
1251 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
1252 {
1253         if (!ldap_state)
1254                 return NT_STATUS_INVALID_PARAMETER;
1255
1256         if (ldap_state->ldap_struct != NULL) {
1257                 ldap_unbind(ldap_state->ldap_struct);
1258                 ldap_state->ldap_struct = NULL;
1259         }
1260
1261         smbldap_delete_state(ldap_state);
1262
1263         DEBUG(5,("The connection to the LDAP server was closed\n"));
1264         /* maybe free the results here --metze */
1265
1266         return NT_STATUS_OK;
1267 }
1268
1269 static bool got_alarm;
1270
1271 static void (*old_handler)(int);
1272
1273 static void gotalarm_sig(int dummy)
1274 {
1275         got_alarm = True;
1276 }
1277
1278 static int another_ldap_try(struct smbldap_state *ldap_state, int *rc,
1279                             int *attempts, time_t endtime)
1280 {
1281         time_t now = time_mono(NULL);
1282         int open_rc = LDAP_SERVER_DOWN;
1283
1284         if (*rc != LDAP_SERVER_DOWN)
1285                 goto no_next;
1286
1287         if (now >= endtime) {
1288                 smbldap_close(ldap_state);
1289                 *rc = LDAP_TIMEOUT;
1290                 goto no_next;
1291         }
1292
1293         if (*attempts == 0) {
1294                 got_alarm = False;
1295                 old_handler = CatchSignal(SIGALRM, gotalarm_sig);
1296                 alarm(endtime - now);
1297
1298                 if (ldap_state->pid != sys_getpid())
1299                         smbldap_close(ldap_state);
1300         }
1301
1302         while (1) {
1303
1304                 if (*attempts != 0)
1305                         smb_msleep(1000);
1306
1307                 *attempts += 1;
1308
1309                 open_rc = smbldap_open(ldap_state);
1310
1311                 if (open_rc == LDAP_SUCCESS) {
1312                         ldap_state->last_use = now;
1313                         return True;
1314                 }
1315
1316                 if (open_rc == LDAP_INSUFFICIENT_ACCESS) {
1317                         /* The fact that we are non-root or any other
1318                          * access-denied condition will not change in the next
1319                          * round of trying */
1320                         *rc = open_rc;
1321                         break;
1322                 }
1323
1324                 if (got_alarm) {
1325                         *rc = LDAP_TIMEOUT;
1326                         break;
1327                 }
1328
1329                 if (open_rc != LDAP_SUCCESS) {
1330                         DEBUG(1, ("Connection to LDAP server failed for the "
1331                                   "%d try!\n", *attempts));
1332                 }
1333         }
1334
1335  no_next:
1336         CatchSignal(SIGALRM, old_handler);
1337         alarm(0);
1338         ldap_state->last_use = now;
1339         return False;
1340 }
1341
1342 /*********************************************************************
1343  ********************************************************************/
1344
1345 static int smbldap_search_ext(struct smbldap_state *ldap_state,
1346                               const char *base, int scope, const char *filter, 
1347                               const char *attrs[], int attrsonly,
1348                               LDAPControl **sctrls, LDAPControl **cctrls, 
1349                               int sizelimit, LDAPMessage **res)
1350 {
1351         int             rc = LDAP_SERVER_DOWN;
1352         int             attempts = 0;
1353         char           *utf8_filter;
1354         time_t          endtime = time_mono(NULL)+lp_ldap_timeout();
1355         struct          timeval timeout;
1356         size_t          converted_size;
1357
1358         SMB_ASSERT(ldap_state);
1359
1360         DEBUG(5,("smbldap_search_ext: base => [%s], filter => [%s], "
1361                  "scope => [%d]\n", base, filter, scope));
1362
1363         if (ldap_state->last_rebind.tv_sec > 0) {
1364                 struct timeval  tval;
1365                 struct timespec ts;
1366                 int64_t tdiff = 0;
1367                 int             sleep_time = 0;
1368
1369                 clock_gettime_mono(&ts);
1370                 tval = convert_timespec_to_timeval(ts);
1371
1372                 tdiff = usec_time_diff(&tval, &ldap_state->last_rebind);
1373                 tdiff /= 1000; /* Convert to milliseconds. */
1374
1375                 sleep_time = lp_ldap_replication_sleep()-(int)tdiff;
1376                 sleep_time = MIN(sleep_time, MAX_LDAP_REPLICATION_SLEEP_TIME);
1377
1378                 if (sleep_time > 0) {
1379                         /* we wait for the LDAP replication */
1380                         DEBUG(5,("smbldap_search_ext: waiting %d milliseconds "
1381                                  "for LDAP replication.\n",sleep_time));
1382                         smb_msleep(sleep_time);
1383                         DEBUG(5,("smbldap_search_ext: go on!\n"));
1384                 }
1385                 ZERO_STRUCT(ldap_state->last_rebind);
1386         }
1387
1388         if (!push_utf8_talloc(talloc_tos(), &utf8_filter, filter, &converted_size)) {
1389                 return LDAP_NO_MEMORY;
1390         }
1391
1392         /* Setup timeout for the ldap_search_ext_s call - local and remote. */
1393         timeout.tv_sec = lp_ldap_timeout();
1394         timeout.tv_usec = 0;
1395
1396         /* Setup alarm timeout.... Do we need both of these ? JRA.
1397          * Yes, I think we do need both of these. The server timeout only
1398          * covers the case where the server's operation takes too long. It
1399          * does not cover the case where the request hangs on its way to the
1400          * server. The server side timeout is not strictly necessary, it's
1401          * just a bit more kind to the server. VL. */
1402
1403         got_alarm = 0;
1404         CatchSignal(SIGALRM, gotalarm_sig);
1405         alarm(lp_ldap_timeout());
1406         /* End setup timeout. */
1407
1408         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1409                 rc = ldap_search_ext_s(ldap_state->ldap_struct, base, scope, 
1410                                        utf8_filter,
1411                                        CONST_DISCARD(char **, attrs),
1412                                        attrsonly, sctrls, cctrls, &timeout,
1413                                        sizelimit, res);
1414                 if (rc != LDAP_SUCCESS) {
1415                         char *ld_error = NULL;
1416                         int ld_errno;
1417
1418                         ldap_get_option(ldap_state->ldap_struct,
1419                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1420
1421                         ldap_get_option(ldap_state->ldap_struct,
1422                                         LDAP_OPT_ERROR_STRING, &ld_error);
1423                         DEBUG(10, ("Failed search for base: %s, error: %d (%s) "
1424                                    "(%s)\n", base, ld_errno,
1425                                    ldap_err2string(rc),
1426                                    ld_error ? ld_error : "unknown"));
1427                         SAFE_FREE(ld_error);
1428
1429                         if (ld_errno == LDAP_SERVER_DOWN) {
1430                                 ldap_unbind(ldap_state->ldap_struct);
1431                                 ldap_state->ldap_struct = NULL;
1432                         }
1433                 }
1434         }
1435
1436         TALLOC_FREE(utf8_filter);
1437
1438         /* Teardown timeout. */
1439         CatchSignal(SIGALRM, SIG_IGN);
1440         alarm(0);
1441
1442         if (got_alarm != 0)
1443                 return LDAP_TIMELIMIT_EXCEEDED;
1444
1445         return rc;
1446 }
1447
1448 int smbldap_search(struct smbldap_state *ldap_state, 
1449                    const char *base, int scope, const char *filter, 
1450                    const char *attrs[], int attrsonly, 
1451                    LDAPMessage **res)
1452 {
1453         return smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1454                                   attrsonly, NULL, NULL, LDAP_NO_LIMIT, res);
1455 }
1456
1457 int smbldap_search_paged(struct smbldap_state *ldap_state, 
1458                          const char *base, int scope, const char *filter, 
1459                          const char **attrs, int attrsonly, int pagesize,
1460                          LDAPMessage **res, void **cookie)
1461 {
1462         LDAPControl     pr;
1463         LDAPControl     **rcontrols;
1464         LDAPControl     *controls[2] = { NULL, NULL};
1465         BerElement      *cookie_be = NULL;
1466         struct berval   *cookie_bv = NULL;
1467         int             tmp = 0, i, rc;
1468         bool            critical = True;
1469
1470         *res = NULL;
1471
1472         DEBUG(3,("smbldap_search_paged: base => [%s], filter => [%s],"
1473                  "scope => [%d], pagesize => [%d]\n",
1474                  base, filter, scope, pagesize));
1475
1476         cookie_be = ber_alloc_t(LBER_USE_DER);
1477         if (cookie_be == NULL) {
1478                 DEBUG(0,("smbldap_create_page_control: ber_alloc_t returns "
1479                          "NULL\n"));
1480                 return LDAP_NO_MEMORY;
1481         }
1482
1483         /* construct cookie */
1484         if (*cookie != NULL) {
1485                 ber_printf(cookie_be, "{iO}", (ber_int_t) pagesize, *cookie);
1486                 ber_bvfree((struct berval *)*cookie); /* don't need it from last time */
1487                 *cookie = NULL;
1488         } else {
1489                 ber_printf(cookie_be, "{io}", (ber_int_t) pagesize, "", 0);
1490         }
1491         ber_flatten(cookie_be, &cookie_bv);
1492
1493         pr.ldctl_oid = CONST_DISCARD(char *, ADS_PAGE_CTL_OID);
1494         pr.ldctl_iscritical = (char) critical;
1495         pr.ldctl_value.bv_len = cookie_bv->bv_len;
1496         pr.ldctl_value.bv_val = cookie_bv->bv_val;
1497
1498         controls[0] = &pr;
1499         controls[1] = NULL;
1500
1501         rc = smbldap_search_ext(ldap_state, base, scope, filter, attrs, 
1502                                  0, controls, NULL, LDAP_NO_LIMIT, res);
1503
1504         ber_free(cookie_be, 1);
1505         ber_bvfree(cookie_bv);
1506
1507         if (rc != 0) {
1508                 DEBUG(3,("smbldap_search_paged: smbldap_search_ext(%s) "
1509                          "failed with [%s]\n", filter, ldap_err2string(rc)));
1510                 goto done;
1511         }
1512
1513         DEBUG(3,("smbldap_search_paged: search was successful\n"));
1514
1515         rc = ldap_parse_result(ldap_state->ldap_struct, *res, NULL, NULL, 
1516                                NULL, NULL, &rcontrols,  0);
1517         if (rc != 0) {
1518                 DEBUG(3,("smbldap_search_paged: ldap_parse_result failed " \
1519                          "with [%s]\n", ldap_err2string(rc)));
1520                 goto done;
1521         }
1522
1523         if (rcontrols == NULL)
1524                 goto done;
1525
1526         for (i=0; rcontrols[i]; i++) {
1527
1528                 if (strcmp(ADS_PAGE_CTL_OID, rcontrols[i]->ldctl_oid) != 0)
1529                         continue;
1530
1531                 cookie_be = ber_init(&rcontrols[i]->ldctl_value);
1532                 ber_scanf(cookie_be,"{iO}", &tmp, &cookie_bv);
1533                 /* the berval is the cookie, but must be freed when it is all
1534                    done */
1535                 if (cookie_bv->bv_len)
1536                         *cookie=ber_bvdup(cookie_bv);
1537                 else
1538                         *cookie=NULL;
1539                 ber_bvfree(cookie_bv);
1540                 ber_free(cookie_be, 1);
1541                 break;
1542         }
1543         ldap_controls_free(rcontrols);
1544 done:   
1545         return rc;
1546 }
1547
1548 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1549 {
1550         int             rc = LDAP_SERVER_DOWN;
1551         int             attempts = 0;
1552         char           *utf8_dn;
1553         time_t          endtime = time_mono(NULL)+lp_ldap_timeout();
1554         size_t          converted_size;
1555
1556         SMB_ASSERT(ldap_state);
1557
1558         DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1559
1560         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1561                 return LDAP_NO_MEMORY;
1562         }
1563
1564         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1565                 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1566                 if (rc != LDAP_SUCCESS) {
1567                         char *ld_error = NULL;
1568                         int ld_errno;
1569
1570                         ldap_get_option(ldap_state->ldap_struct,
1571                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1572
1573                         ldap_get_option(ldap_state->ldap_struct,
1574                                         LDAP_OPT_ERROR_STRING, &ld_error);
1575                         DEBUG(10, ("Failed to modify dn: %s, error: %d (%s) "
1576                                    "(%s)\n", dn, ld_errno,
1577                                    ldap_err2string(rc),
1578                                    ld_error ? ld_error : "unknown"));
1579                         SAFE_FREE(ld_error);
1580
1581                         if (ld_errno == LDAP_SERVER_DOWN) {
1582                                 ldap_unbind(ldap_state->ldap_struct);
1583                                 ldap_state->ldap_struct = NULL;
1584                         }
1585                 }
1586         }
1587
1588         TALLOC_FREE(utf8_dn);
1589         return rc;
1590 }
1591
1592 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1593 {
1594         int             rc = LDAP_SERVER_DOWN;
1595         int             attempts = 0;
1596         char           *utf8_dn;
1597         time_t          endtime = time_mono(NULL)+lp_ldap_timeout();
1598         size_t          converted_size;
1599
1600         SMB_ASSERT(ldap_state);
1601
1602         DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1603
1604         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1605                 return LDAP_NO_MEMORY;
1606         }
1607
1608         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1609                 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1610                 if (rc != LDAP_SUCCESS) {
1611                         char *ld_error = NULL;
1612                         int ld_errno;
1613
1614                         ldap_get_option(ldap_state->ldap_struct,
1615                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1616
1617                         ldap_get_option(ldap_state->ldap_struct,
1618                                         LDAP_OPT_ERROR_STRING, &ld_error);
1619                         DEBUG(10, ("Failed to add dn: %s, error: %d (%s) "
1620                                    "(%s)\n", dn, ld_errno,
1621                                    ldap_err2string(rc),
1622                                    ld_error ? ld_error : "unknown"));
1623                         SAFE_FREE(ld_error);
1624
1625                         if (ld_errno == LDAP_SERVER_DOWN) {
1626                                 ldap_unbind(ldap_state->ldap_struct);
1627                                 ldap_state->ldap_struct = NULL;
1628                         }
1629                 }
1630         }
1631
1632         TALLOC_FREE(utf8_dn);
1633         return rc;
1634 }
1635
1636 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1637 {
1638         int             rc = LDAP_SERVER_DOWN;
1639         int             attempts = 0;
1640         char           *utf8_dn;
1641         time_t          endtime = time_mono(NULL)+lp_ldap_timeout();
1642         size_t          converted_size;
1643
1644         SMB_ASSERT(ldap_state);
1645
1646         DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1647
1648         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1649                 return LDAP_NO_MEMORY;
1650         }
1651
1652         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1653                 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1654                 if (rc != LDAP_SUCCESS) {
1655                         char *ld_error = NULL;
1656                         int ld_errno;
1657
1658                         ldap_get_option(ldap_state->ldap_struct,
1659                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1660
1661                         ldap_get_option(ldap_state->ldap_struct,
1662                                         LDAP_OPT_ERROR_STRING, &ld_error);
1663                         DEBUG(10, ("Failed to delete dn: %s, error: %d (%s) "
1664                                    "(%s)\n", dn, ld_errno,
1665                                    ldap_err2string(rc),
1666                                    ld_error ? ld_error : "unknown"));
1667                         SAFE_FREE(ld_error);
1668
1669                         if (ld_errno == LDAP_SERVER_DOWN) {
1670                                 ldap_unbind(ldap_state->ldap_struct);
1671                                 ldap_state->ldap_struct = NULL;
1672                         }
1673                 }
1674         }
1675
1676         TALLOC_FREE(utf8_dn);
1677         return rc;
1678 }
1679
1680 int smbldap_extended_operation(struct smbldap_state *ldap_state, 
1681                                LDAP_CONST char *reqoid, struct berval *reqdata, 
1682                                LDAPControl **serverctrls, LDAPControl **clientctrls, 
1683                                char **retoidp, struct berval **retdatap)
1684 {
1685         int             rc = LDAP_SERVER_DOWN;
1686         int             attempts = 0;
1687         time_t          endtime = time_mono(NULL)+lp_ldap_timeout();
1688
1689         if (!ldap_state)
1690                 return (-1);
1691
1692         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1693                 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid,
1694                                                reqdata, serverctrls,
1695                                                clientctrls, retoidp, retdatap);
1696                 if (rc != LDAP_SUCCESS) {
1697                         char *ld_error = NULL;
1698                         int ld_errno;
1699
1700                         ldap_get_option(ldap_state->ldap_struct,
1701                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1702
1703                         ldap_get_option(ldap_state->ldap_struct,
1704                                         LDAP_OPT_ERROR_STRING, &ld_error);
1705                         DEBUG(10, ("Extended operation failed with error: "
1706                                    "%d (%s) (%s)\n", ld_errno,
1707                                    ldap_err2string(rc),
1708                                    ld_error ? ld_error : "unknown"));
1709                         SAFE_FREE(ld_error);
1710
1711                         if (ld_errno == LDAP_SERVER_DOWN) {
1712                                 ldap_unbind(ldap_state->ldap_struct);
1713                                 ldap_state->ldap_struct = NULL;
1714                         }
1715                 }
1716         }
1717
1718         return rc;
1719 }
1720
1721 /*******************************************************************
1722  run the search by name.
1723 ******************************************************************/
1724 int smbldap_search_suffix (struct smbldap_state *ldap_state,
1725                            const char *filter, const char **search_attr,
1726                            LDAPMessage ** result)
1727 {
1728         return smbldap_search(ldap_state, lp_ldap_suffix(), LDAP_SCOPE_SUBTREE,
1729                               filter, search_attr, 0, result);
1730 }
1731
1732 static void smbldap_idle_fn(struct event_context *event_ctx,
1733                             struct timed_event *te,
1734                             struct timeval now_abs,
1735                             void *private_data)
1736 {
1737         struct smbldap_state *state = (struct smbldap_state *)private_data;
1738
1739         TALLOC_FREE(state->idle_event);
1740
1741         if (state->ldap_struct == NULL) {
1742                 DEBUG(10,("ldap connection not connected...\n"));
1743                 return;
1744         }
1745
1746         if ((state->last_use+SMBLDAP_IDLE_TIME) > time_mono(NULL)) {
1747                 DEBUG(10,("ldap connection not idle...\n"));
1748
1749                 /* this needs to be made monotonic clock aware inside tevent: */
1750                 state->idle_event = event_add_timed(
1751                         event_ctx, NULL,
1752                         timeval_add(&now_abs, SMBLDAP_IDLE_TIME, 0),
1753                         smbldap_idle_fn,
1754                         private_data);
1755                 return;
1756         }
1757
1758         DEBUG(7,("ldap connection idle...closing connection\n"));
1759         smbldap_close(state);
1760 }
1761
1762 /**********************************************************************
1763  Housekeeping
1764  *********************************************************************/
1765
1766 void smbldap_free_struct(struct smbldap_state **ldap_state) 
1767 {
1768         smbldap_close(*ldap_state);
1769
1770         if ((*ldap_state)->bind_secret) {
1771                 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1772         }
1773
1774         SAFE_FREE((*ldap_state)->bind_dn);
1775         SAFE_FREE((*ldap_state)->bind_secret);
1776
1777         TALLOC_FREE((*ldap_state)->idle_event);
1778
1779         *ldap_state = NULL;
1780
1781         /* No need to free any further, as it is talloc()ed */
1782 }
1783
1784
1785 /**********************************************************************
1786  Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1787  *********************************************************************/
1788
1789 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, struct event_context *event_ctx,
1790                       const char *location,
1791                       struct smbldap_state **smbldap_state)
1792 {
1793         *smbldap_state = TALLOC_ZERO_P(mem_ctx, struct smbldap_state);
1794         if (!*smbldap_state) {
1795                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1796                 return NT_STATUS_NO_MEMORY;
1797         }
1798
1799         if (location) {
1800                 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1801         } else {
1802                 (*smbldap_state)->uri = "ldap://localhost";
1803         }
1804
1805         (*smbldap_state)->event_context = event_ctx;
1806
1807         return NT_STATUS_OK;
1808 }
1809
1810  char *smbldap_talloc_dn(TALLOC_CTX *mem_ctx, LDAP *ld,
1811                          LDAPMessage *entry)
1812 {
1813         char *utf8_dn, *unix_dn;
1814         size_t converted_size;
1815
1816         utf8_dn = ldap_get_dn(ld, entry);
1817         if (!utf8_dn) {
1818                 DEBUG (5, ("smbldap_talloc_dn: ldap_get_dn failed\n"));
1819                 return NULL;
1820         }
1821         if (!pull_utf8_talloc(mem_ctx, &unix_dn, utf8_dn, &converted_size)) {
1822                 DEBUG (0, ("smbldap_talloc_dn: String conversion failure utf8 "
1823                            "[%s]\n", utf8_dn));
1824                 return NULL;
1825         }
1826         ldap_memfree(utf8_dn);
1827         return unix_dn;
1828 }
1829
1830 /*******************************************************************
1831  Check if root-dse has a certain Control or Extension
1832 ********************************************************************/
1833
1834 static bool smbldap_check_root_dse(LDAP *ld, const char **attrs, const char *value) 
1835 {
1836         LDAPMessage *msg = NULL;
1837         LDAPMessage *entry = NULL;
1838         char **values = NULL;
1839         int rc, num_result, num_values, i;
1840         bool result = False;
1841
1842         if (!attrs[0]) {
1843                 DEBUG(3,("smbldap_check_root_dse: nothing to look for\n"));
1844                 return False;
1845         }
1846
1847         if (!strequal(attrs[0], "supportedExtension") && 
1848             !strequal(attrs[0], "supportedControl") && 
1849             !strequal(attrs[0], "namingContexts")) {
1850                 DEBUG(3,("smbldap_check_root_dse: no idea what to query root-dse for: %s ?\n", attrs[0]));
1851                 return False;
1852         }
1853
1854         rc = ldap_search_s(ld, "", LDAP_SCOPE_BASE, 
1855                            "(objectclass=*)", CONST_DISCARD(char **, attrs), 0 , &msg);
1856
1857         if (rc != LDAP_SUCCESS) {
1858                 DEBUG(3,("smbldap_check_root_dse: Could not search rootDSE\n"));
1859                 return False;
1860         }
1861
1862         num_result = ldap_count_entries(ld, msg);
1863
1864         if (num_result != 1) {
1865                 DEBUG(3,("smbldap_check_root_dse: Expected one rootDSE, got %d\n", num_result));
1866                 goto done;
1867         }
1868
1869         entry = ldap_first_entry(ld, msg);
1870
1871         if (entry == NULL) {
1872                 DEBUG(3,("smbldap_check_root_dse: Could not retrieve rootDSE\n"));
1873                 goto done;
1874         }
1875
1876         values = ldap_get_values(ld, entry, attrs[0]);
1877
1878         if (values == NULL) {
1879                 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not support any %s\n", attrs[0]));
1880                 goto done;
1881         }
1882
1883         num_values = ldap_count_values(values);
1884
1885         if (num_values == 0) {
1886                 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not have any %s\n", attrs[0]));
1887                 goto done;
1888         }
1889
1890         for (i=0; i<num_values; i++) {
1891                 if (strcmp(values[i], value) == 0)
1892                         result = True;
1893         }
1894
1895
1896  done:
1897         if (values != NULL)
1898                 ldap_value_free(values);
1899         if (msg != NULL)
1900                 ldap_msgfree(msg);
1901
1902         return result;
1903
1904 }
1905
1906 /*******************************************************************
1907  Check if LDAP-Server supports a certain Control (OID in string format)
1908 ********************************************************************/
1909
1910 bool smbldap_has_control(LDAP *ld, const char *control)
1911 {
1912         const char *attrs[] = { "supportedControl", NULL };
1913         return smbldap_check_root_dse(ld, attrs, control);
1914 }
1915
1916 /*******************************************************************
1917  Check if LDAP-Server supports a certain Extension (OID in string format)
1918 ********************************************************************/
1919
1920 bool smbldap_has_extension(LDAP *ld, const char *extension)
1921 {
1922         const char *attrs[] = { "supportedExtension", NULL };
1923         return smbldap_check_root_dse(ld, attrs, extension);
1924 }
1925
1926 /*******************************************************************
1927  Check if LDAP-Server holds a given namingContext
1928 ********************************************************************/
1929
1930 bool smbldap_has_naming_context(LDAP *ld, const char *naming_context)
1931 {
1932         const char *attrs[] = { "namingContexts", NULL };
1933         return smbldap_check_root_dse(ld, attrs, naming_context);
1934 }
1935
1936 bool smbldap_set_creds(struct smbldap_state *ldap_state, bool anon, const char *dn, const char *secret)
1937 {
1938         ldap_state->anonymous = anon;
1939
1940         /* free any previously set credential */
1941
1942         SAFE_FREE(ldap_state->bind_dn);
1943         if (ldap_state->bind_secret) {
1944                 /* make sure secrets are zeroed out of memory */
1945                 memset(ldap_state->bind_secret, '\0', strlen(ldap_state->bind_secret));
1946                 SAFE_FREE(ldap_state->bind_secret);
1947         }
1948
1949         if ( ! anon) {
1950                 ldap_state->bind_dn = SMB_STRDUP(dn);
1951                 ldap_state->bind_secret = SMB_STRDUP(secret);
1952         }
1953
1954         return True;
1955 }