import HEAD into svn+ssh://svn.samba.org/home/svn/samba/trunk
[metze/old/v3-2-winbind-ndr.git] / source / lib / smbldap.c
1 /* 
2    Unix SMB/CIFS mplementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Jean François Micouleau        1998
5    Copyright (C) Gerald Carter                  2001-2003
6    Copyright (C) Shahms King                    2001
7    Copyright (C) Andrew Bartlett                2002-2003
8    Copyright (C) Stefan (metze) Metzmacher      2002-2003
9     
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23    
24 */
25
26 #include "includes.h"
27 #include "smbldap.h"
28
29 #ifndef LDAP_OPT_SUCCESS
30 #define LDAP_OPT_SUCCESS 0
31 #endif
32
33 /* Try not to hit the up or down server forever */
34
35 #define SMBLDAP_DONT_PING_TIME 10       /* ping only all 10 seconds */
36 #define SMBLDAP_NUM_RETRIES 8           /* retry only 8 times */
37
38 #define SMBLDAP_IDLE_TIME 150           /* After 2.5 minutes disconnect */
39
40
41 /* attributes used by Samba 2.2 */
42
43 ATTRIB_MAP_ENTRY attrib_map_v22[] = {
44         { LDAP_ATTR_UID,                "uid"           },
45         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
46         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
47         { LDAP_ATTR_UNIX_HOME,          "homeDirectory" },
48         { LDAP_ATTR_PWD_LAST_SET,       "pwdLastSet"    },
49         { LDAP_ATTR_PWD_CAN_CHANGE,     "pwdCanChange"  },
50         { LDAP_ATTR_PWD_MUST_CHANGE,    "pwdMustChange" },
51         { LDAP_ATTR_LOGON_TIME,         "logonTime"     },
52         { LDAP_ATTR_LOGOFF_TIME,        "logoffTime"    },
53         { LDAP_ATTR_KICKOFF_TIME,       "kickoffTime"   },
54         { LDAP_ATTR_CN,                 "cn"            },
55         { LDAP_ATTR_DISPLAY_NAME,       "displayName"   },
56         { LDAP_ATTR_HOME_PATH,          "smbHome"       },
57         { LDAP_ATTR_HOME_DRIVE,         "homeDrives"    },
58         { LDAP_ATTR_LOGON_SCRIPT,       "scriptPath"    },
59         { LDAP_ATTR_PROFILE_PATH,       "profilePath"   },
60         { LDAP_ATTR_DESC,               "description"   },
61         { LDAP_ATTR_USER_WKS,           "userWorkstations"},
62         { LDAP_ATTR_USER_RID,           "rid"           },
63         { LDAP_ATTR_PRIMARY_GROUP_RID,  "primaryGroupID"},
64         { LDAP_ATTR_LMPW,               "lmPassword"    },
65         { LDAP_ATTR_NTPW,               "ntPassword"    },
66         { LDAP_ATTR_DOMAIN,             "domain"        },
67         { LDAP_ATTR_OBJCLASS,           "objectClass"   },
68         { LDAP_ATTR_ACB_INFO,           "acctFlags"     },
69         { LDAP_ATTR_LIST_END,           NULL            }
70 };
71
72 /* attributes used by Samba 3.0's sambaSamAccount */
73
74 ATTRIB_MAP_ENTRY attrib_map_v30[] = {
75         { LDAP_ATTR_UID,                "uid"                   },
76         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
77         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
78         { LDAP_ATTR_UNIX_HOME,          "homeDirectory"         },
79         { LDAP_ATTR_PWD_LAST_SET,       "sambaPwdLastSet"       },
80         { LDAP_ATTR_PWD_CAN_CHANGE,     "sambaPwdCanChange"     },
81         { LDAP_ATTR_PWD_MUST_CHANGE,    "sambaPwdMustChange"    },
82         { LDAP_ATTR_LOGON_TIME,         "sambaLogonTime"        },
83         { LDAP_ATTR_LOGOFF_TIME,        "sambaLogoffTime"       },
84         { LDAP_ATTR_KICKOFF_TIME,       "sambaKickoffTime"      },
85         { LDAP_ATTR_CN,                 "cn"                    },
86         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
87         { LDAP_ATTR_HOME_DRIVE,         "sambaHomeDrive"        },
88         { LDAP_ATTR_HOME_PATH,          "sambaHomePath"         },
89         { LDAP_ATTR_LOGON_SCRIPT,       "sambaLogonScript"      },
90         { LDAP_ATTR_PROFILE_PATH,       "sambaProfilePath"      },
91         { LDAP_ATTR_DESC,               "description"           },
92         { LDAP_ATTR_USER_WKS,           "sambaUserWorkstations" },
93         { LDAP_ATTR_USER_SID,           LDAP_ATTRIBUTE_SID      },
94         { LDAP_ATTR_PRIMARY_GROUP_SID,  "sambaPrimaryGroupSID"  },
95         { LDAP_ATTR_LMPW,               "sambaLMPassword"       },
96         { LDAP_ATTR_NTPW,               "sambaNTPassword"       },
97         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
98         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
99         { LDAP_ATTR_ACB_INFO,           "sambaAcctFlags"        },
100         { LDAP_ATTR_MUNGED_DIAL,        "sambaMungedDial"       },
101         { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
102         { LDAP_ATTR_BAD_PASSWORD_TIME,  "sambaBadPasswordTime"  },
103         { LDAP_ATTR_MOD_TIMESTAMP,      "modifyTimestamp"       },
104         { LDAP_ATTR_LIST_END,           NULL                    }
105 };
106
107 /* attributes used for allocating RIDs */
108
109 ATTRIB_MAP_ENTRY dominfo_attr_list[] = {
110         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
111         { LDAP_ATTR_NEXT_RID,           "sambaNextRid"          },
112         { LDAP_ATTR_NEXT_USERRID,       "sambaNextUserRid"      },
113         { LDAP_ATTR_NEXT_GROUPRID,      "sambaNextGroupRid"     },
114         { LDAP_ATTR_DOM_SID,            LDAP_ATTRIBUTE_SID      },
115         { LDAP_ATTR_ALGORITHMIC_RID_BASE,"sambaAlgorithmicRidBase"},
116         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
117         { LDAP_ATTR_LIST_END,           NULL                    },
118 };
119
120 /* Samba 3.0 group mapping attributes */
121
122 ATTRIB_MAP_ENTRY groupmap_attr_list[] = {
123         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
124         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
125         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
126         { LDAP_ATTR_SID_LIST,           "sambaSIDList"          },
127         { LDAP_ATTR_DESC,               "description"           },
128         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
129         { LDAP_ATTR_CN,                 "cn"                    },
130         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
131         { LDAP_ATTR_LIST_END,           NULL                    }       
132 };
133
134 ATTRIB_MAP_ENTRY groupmap_attr_list_to_delete[] = {
135         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
136         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
137         { LDAP_ATTR_DESC,               "description"           },
138         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
139         { LDAP_ATTR_SID_LIST,           "sambaSIDList"          },
140         { LDAP_ATTR_LIST_END,           NULL                    }       
141 };
142
143 /* idmap_ldap sambaUnixIdPool */
144
145 ATTRIB_MAP_ENTRY idpool_attr_list[] = {
146         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
147         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
148         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
149         { LDAP_ATTR_LIST_END,           NULL                    }       
150 };
151
152 ATTRIB_MAP_ENTRY sidmap_attr_list[] = {
153         { LDAP_ATTR_SID,                LDAP_ATTRIBUTE_SID      },
154         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
155         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
156         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
157         { LDAP_ATTR_LIST_END,           NULL                    }       
158 };
159
160 /* privileges */
161
162 ATTRIB_MAP_ENTRY privilege_attr_list[] = {
163         { LDAP_ATTR_CN,                 "sambaPrivName"         },
164         { LDAP_ATTR_SID_LIST,           LDAP_ATTRIBUTE_SID_LIST },
165         { LDAP_ATTR_DESC,               "description"           },
166         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
167         { LDAP_ATTR_LIST_END,           NULL                    }
168 };
169
170 /**********************************************************************
171  perform a simple table lookup and return the attribute name 
172  **********************************************************************/
173  
174  const char* get_attr_key2string( ATTRIB_MAP_ENTRY table[], int key )
175 {
176         int i = 0;
177         
178         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
179                 if ( table[i].attrib == key )
180                         return table[i].name;
181                 i++;
182         }
183         
184         return NULL;
185 }
186
187
188 /**********************************************************************
189  Return the list of attribute names from a mapping table
190  **********************************************************************/
191
192  char** get_attr_list( ATTRIB_MAP_ENTRY table[] )
193 {
194         char **names;
195         int i = 0;
196         
197         while ( table[i].attrib != LDAP_ATTR_LIST_END )
198                 i++;
199         i++;
200
201         names = (char**)malloc( sizeof(char*)*i );
202         if ( !names ) {
203                 DEBUG(0,("get_attr_list: out of memory\n"));
204                 return NULL;
205         }
206
207         i = 0;
208         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
209                 names[i] = strdup( table[i].name );
210                 i++;
211         }
212         names[i] = NULL;
213         
214         return names;
215 }
216
217 /*********************************************************************
218  Cleanup 
219  ********************************************************************/
220
221  void free_attr_list( char **list )
222 {
223         int i = 0;
224
225         if ( !list )
226                 return; 
227
228         while ( list[i] ) {
229                 SAFE_FREE( list[i] );
230                 i+=1;
231         }
232
233         SAFE_FREE( list );
234 }
235
236 /*******************************************************************
237  find the ldap password
238 ******************************************************************/
239 static BOOL fetch_ldap_pw(char **dn, char** pw)
240 {
241         char *key = NULL;
242         size_t size;
243         
244         *dn = smb_xstrdup(lp_ldap_admin_dn());
245         
246         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, *dn) < 0) {
247                 SAFE_FREE(*dn);
248                 DEBUG(0, ("fetch_ldap_pw: asprintf failed!\n"));
249         }
250         
251         *pw=secrets_fetch(key, &size);
252         SAFE_FREE(key);
253
254         if (!size) {
255                 /* Upgrade 2.2 style entry */
256                 char *p;
257                 char* old_style_key = strdup(*dn);
258                 char *data;
259                 fstring old_style_pw;
260                 
261                 if (!old_style_key) {
262                         DEBUG(0, ("fetch_ldap_pw: strdup failed!\n"));
263                         return False;
264                 }
265
266                 for (p=old_style_key; *p; p++)
267                         if (*p == ',') *p = '/';
268         
269                 data=secrets_fetch(old_style_key, &size);
270                 if (!size && size < sizeof(old_style_pw)) {
271                         DEBUG(0,("fetch_ldap_pw: neither ldap secret retrieved!\n"));
272                         SAFE_FREE(old_style_key);
273                         SAFE_FREE(*dn);
274                         return False;
275                 }
276
277                 size = MIN(size, sizeof(fstring)-1);
278                 strncpy(old_style_pw, data, size);
279                 old_style_pw[size] = 0;
280
281                 SAFE_FREE(data);
282
283                 if (!secrets_store_ldap_pw(*dn, old_style_pw)) {
284                         DEBUG(0,("fetch_ldap_pw: ldap secret could not be upgraded!\n"));
285                         SAFE_FREE(old_style_key);
286                         SAFE_FREE(*dn);
287                         return False;                   
288                 }
289                 if (!secrets_delete(old_style_key)) {
290                         DEBUG(0,("fetch_ldap_pw: old ldap secret could not be deleted!\n"));
291                 }
292
293                 SAFE_FREE(old_style_key);
294
295                 *pw = smb_xstrdup(old_style_pw);                
296         }
297         
298         return True;
299 }
300
301 /*******************************************************************
302  Search an attribute and return the first value found.
303 ******************************************************************/
304
305  BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
306                                     const char *attribute, char *value,
307                                     int max_len)
308 {
309         char **values;
310         
311         if ( !attribute )
312                 return False;
313                 
314         value[0] = '\0';
315
316         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
317                 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
318                 
319                 return False;
320         }
321         
322         if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, max_len, False) == (size_t)-1) {
323                 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n", 
324                           attribute, values[0]));
325                 ldap_value_free(values);
326                 return False;
327         }
328         
329         ldap_value_free(values);
330 #ifdef DEBUG_PASSWORDS
331         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
332 #endif  
333         return True;
334 }
335
336  BOOL smbldap_get_single_pstring (LDAP * ldap_struct, LDAPMessage * entry,
337                                   const char *attribute, pstring value)
338 {
339         return smbldap_get_single_attribute(ldap_struct, entry,
340                                             attribute, value, 
341                                             sizeof(pstring));
342 }
343
344 /************************************************************************
345  Routine to manage the LDAPMod structure array
346  manage memory used by the array, by each struct, and values
347  ***********************************************************************/
348
349  void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
350 {
351         LDAPMod **mods;
352         int i;
353         int j;
354
355         mods = *modlist;
356
357         /* sanity checks on the mod values */
358
359         if (attribute == NULL || *attribute == '\0')
360                 return; 
361 #if 0   /* commented out after discussion with abartlet.  Do not reenable.
362            left here so other so re-add similar code   --jerry */
363         if (value == NULL || *value == '\0')
364                 return;
365 #endif
366
367         if (mods == NULL) 
368         {
369                 mods = (LDAPMod **) malloc(sizeof(LDAPMod *));
370                 if (mods == NULL)
371                 {
372                         DEBUG(0, ("make_a_mod: out of memory!\n"));
373                         return;
374                 }
375                 mods[0] = NULL;
376         }
377
378         for (i = 0; mods[i] != NULL; ++i) {
379                 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
380                         break;
381         }
382
383         if (mods[i] == NULL)
384         {
385                 mods = (LDAPMod **) Realloc (mods, (i + 2) * sizeof (LDAPMod *));
386                 if (mods == NULL)
387                 {
388                         DEBUG(0, ("make_a_mod: out of memory!\n"));
389                         return;
390                 }
391                 mods[i] = (LDAPMod *) malloc(sizeof(LDAPMod));
392                 if (mods[i] == NULL)
393                 {
394                         DEBUG(0, ("make_a_mod: out of memory!\n"));
395                         return;
396                 }
397                 mods[i]->mod_op = modop;
398                 mods[i]->mod_values = NULL;
399                 mods[i]->mod_type = strdup(attribute);
400                 mods[i + 1] = NULL;
401         }
402
403         if (value != NULL)
404         {
405                 char *utf8_value = NULL;
406
407                 j = 0;
408                 if (mods[i]->mod_values != NULL) {
409                         for (; mods[i]->mod_values[j] != NULL; j++);
410                 }
411                 mods[i]->mod_values = (char **)Realloc(mods[i]->mod_values,
412                                                (j + 2) * sizeof (char *));
413                                                
414                 if (mods[i]->mod_values == NULL) {
415                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
416                         return;
417                 }
418
419                 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
420                         DEBUG (0, ("make_a_mod: String conversion failure!\n"));
421                         return;
422                 }
423
424                 mods[i]->mod_values[j] = utf8_value;
425
426                 mods[i]->mod_values[j + 1] = NULL;
427         }
428         *modlist = mods;
429 }
430
431 /**********************************************************************
432   Set attribute to newval in LDAP, regardless of what value the
433   attribute had in LDAP before.
434 *********************************************************************/
435
436  void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
437                       LDAPMod ***mods,
438                       const char *attribute, const char *newval)
439 {
440         char oldval[2048]; /* current largest allowed value is mungeddial */
441         BOOL existed;
442
443         if (existing != NULL) {
444                 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval, sizeof(oldval));
445         } else {
446                 existed = False;
447                 *oldval = '\0';
448         }
449
450         /* all of our string attributes are case insensitive */
451         
452         if (existed && newval && (StrCaseCmp(oldval, newval) == 0)) {
453                 
454                 /* Believe it or not, but LDAP will deny a delete and
455                    an add at the same time if the values are the
456                    same... */
457                 return;
458         }
459
460         if (existed) {
461                 /* There has been no value before, so don't delete it.
462                  * Here's a possible race: We might end up with
463                  * duplicate attributes */
464                 /* By deleting exactly the value we found in the entry this
465                  * should be race-free in the sense that the LDAP-Server will
466                  * deny the complete operation if somebody changed the
467                  * attribute behind our back. */
468                 /* This will also allow modifying single valued attributes 
469                  * in Novell NDS. In NDS you have to first remove attribute and then
470                  * you could add new value */
471                 
472                 smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, oldval);
473         }
474
475         /* Regardless of the real operation (add or modify)
476            we add the new value here. We rely on deleting
477            the old value, should it exist. */
478
479         if ((newval != NULL) && (strlen(newval) > 0)) {
480                 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
481         }
482 }
483
484 /**********************************************************************
485  Some varients of the LDAP rebind code do not pass in the third 'arg' 
486  pointer to a void*, so we try and work around it by assuming that the 
487  value of the 'LDAP *' pointer is the same as the one we had passed in
488  **********************************************************************/
489
490 struct smbldap_state_lookup {
491         LDAP *ld;
492         struct smbldap_state *smbldap_state;
493         struct smbldap_state_lookup *prev, *next;
494 };
495
496 static struct smbldap_state_lookup *smbldap_state_lookup_list;
497
498 static struct smbldap_state *smbldap_find_state(LDAP *ld) 
499 {
500         struct smbldap_state_lookup *t;
501
502         for (t = smbldap_state_lookup_list; t; t = t->next) {
503                 if (t->ld == ld) {
504                         return t->smbldap_state;
505                 }
506         }
507         return NULL;
508 }
509
510 static void smbldap_delete_state(struct smbldap_state *smbldap_state) 
511 {
512         struct smbldap_state_lookup *t;
513
514         for (t = smbldap_state_lookup_list; t; t = t->next) {
515                 if (t->smbldap_state == smbldap_state) {
516                         DLIST_REMOVE(smbldap_state_lookup_list, t);
517                         SAFE_FREE(t);
518                         return;
519                 }
520         }
521 }
522
523 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state) 
524 {
525         struct smbldap_state *tmp_ldap_state;
526         struct smbldap_state_lookup *t;
527         struct smbldap_state_lookup *tmp;
528         
529         if ((tmp_ldap_state = smbldap_find_state(ld))) {
530                 SMB_ASSERT(tmp_ldap_state == smbldap_state);
531                 return;
532         }
533
534         t = smb_xmalloc(sizeof(*t));
535         ZERO_STRUCTP(t);
536         
537         DLIST_ADD_END(smbldap_state_lookup_list, t, tmp);
538         t->ld = ld;
539         t->smbldap_state = smbldap_state;
540 }
541
542 /*******************************************************************
543  open a connection to the ldap server.
544 ******************************************************************/
545 static int smbldap_open_connection (struct smbldap_state *ldap_state)
546
547 {
548         int rc = LDAP_SUCCESS;
549         int version;
550         BOOL ldap_v3 = False;
551         LDAP **ldap_struct = &ldap_state->ldap_struct;
552
553 #ifdef HAVE_LDAP_INITIALIZE
554         DEBUG(10, ("smbldap_open_connection: %s\n", ldap_state->uri));
555         
556         if ((rc = ldap_initialize(ldap_struct, ldap_state->uri)) != LDAP_SUCCESS) {
557                 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
558                 return rc;
559         }
560 #else 
561
562         /* Parse the string manually */
563
564         {
565                 int port = 0;
566                 fstring protocol;
567                 fstring host;
568                 const char *p = ldap_state->uri; 
569                 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
570                 
571                 /* skip leading "URL:" (if any) */
572                 if ( strnequal( p, "URL:", 4 ) ) {
573                         p += 4;
574                 }
575                 
576                 sscanf(p, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
577                 
578                 if (port == 0) {
579                         if (strequal(protocol, "ldap")) {
580                                 port = LDAP_PORT;
581                         } else if (strequal(protocol, "ldaps")) {
582                                 port = LDAPS_PORT;
583                         } else {
584                                 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
585                         }
586                 }
587                 
588                 if ((*ldap_struct = ldap_init(host, port)) == NULL)     {
589                         DEBUG(0, ("ldap_init failed !\n"));
590                         return LDAP_OPERATIONS_ERROR;
591                 }
592                 
593                 if (strequal(protocol, "ldaps")) {
594 #ifdef LDAP_OPT_X_TLS
595                         int tls = LDAP_OPT_X_TLS_HARD;
596                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
597                         {
598                                 DEBUG(0, ("Failed to setup a TLS session\n"));
599                         }
600                         
601                         DEBUG(3,("LDAPS option set...!\n"));
602 #else
603                         DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
604                         return LDAP_OPERATIONS_ERROR;
605 #endif
606                 }
607         }
608 #endif
609
610         /* Store the LDAP pointer in a lookup list */
611
612         smbldap_store_state(*ldap_struct, ldap_state);
613
614         /* Upgrade to LDAPv3 if possible */
615
616         if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
617         {
618                 if (version != LDAP_VERSION3)
619                 {
620                         version = LDAP_VERSION3;
621                         if (ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS) {
622                                 ldap_v3 = True;
623                         }
624                 } else {
625                         ldap_v3 = True;
626                 }
627         }
628
629         if (lp_ldap_ssl() == LDAP_SSL_START_TLS) {
630 #ifdef LDAP_OPT_X_TLS
631                 if (ldap_v3) {
632                         if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
633                         {
634                                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
635                                          ldap_err2string(rc)));
636                                 return rc;
637                         }
638                         DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
639                 } else {
640                         
641                         DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
642                         return LDAP_OPERATIONS_ERROR;
643                 }
644 #else
645                 DEBUG(0,("smbldap_open_connection: StartTLS not supported by LDAP client libraries!\n"));
646                 return LDAP_OPERATIONS_ERROR;
647 #endif
648         }
649
650         DEBUG(2, ("smbldap_open_connection: connection opened\n"));
651         return rc;
652 }
653
654
655 /*******************************************************************
656  a rebind function for authenticated referrals
657  This version takes a void* that we can shove useful stuff in :-)
658 ******************************************************************/
659 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
660 #else
661 static int rebindproc_with_state  (LDAP * ld, char **whop, char **credp, 
662                                    int *methodp, int freeit, void *arg)
663 {
664         struct smbldap_state *ldap_state = arg;
665         
666         /** @TODO Should we be doing something to check what servers we rebind to?
667             Could we get a referral to a machine that we don't want to give our
668             username and password to? */
669         
670         if (freeit) {
671                 SAFE_FREE(*whop);
672                 memset(*credp, '\0', strlen(*credp));
673                 SAFE_FREE(*credp);
674         } else {
675                 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n", 
676                           ldap_state->bind_dn));
677
678                 *whop = strdup(ldap_state->bind_dn);
679                 if (!*whop) {
680                         return LDAP_NO_MEMORY;
681                 }
682                 *credp = strdup(ldap_state->bind_secret);
683                 if (!*credp) {
684                         SAFE_FREE(*whop);
685                         return LDAP_NO_MEMORY;
686                 }
687                 *methodp = LDAP_AUTH_SIMPLE;
688         }
689
690         gettimeofday(&(ldap_state->last_rebind),NULL);
691                 
692         return 0;
693 }
694 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
695
696 /*******************************************************************
697  a rebind function for authenticated referrals
698  This version takes a void* that we can shove useful stuff in :-)
699  and actually does the connection.
700 ******************************************************************/
701 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
702 static int rebindproc_connect_with_state (LDAP *ldap_struct, 
703                                           LDAP_CONST char *url, 
704                                           ber_tag_t request,
705                                           ber_int_t msgid, void *arg)
706 {
707         struct smbldap_state *ldap_state = arg;
708         int rc;
709         DEBUG(5,("rebindproc_connect_with_state: Rebinding as \"%s\"\n", 
710                  ldap_state->bind_dn));
711         
712         /** @TODO Should we be doing something to check what servers we rebind to?
713             Could we get a referral to a machine that we don't want to give our
714             username and password to? */
715
716         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
717         
718         gettimeofday(&(ldap_state->last_rebind),NULL);
719
720         return rc;
721 }
722 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
723
724 /*******************************************************************
725  Add a rebind function for authenticated referrals
726 ******************************************************************/
727 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
728 #else
729 # if LDAP_SET_REBIND_PROC_ARGS == 2
730 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
731                        int *method, int freeit )
732 {
733         struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
734
735         return rebindproc_with_state(ldap_struct, whop, credp,
736                                      method, freeit, ldap_state);
737         
738 }
739 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
740 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
741
742 /*******************************************************************
743  a rebind function for authenticated referrals
744  this also does the connection, but no void*.
745 ******************************************************************/
746 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
747 # if LDAP_SET_REBIND_PROC_ARGS == 2
748 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
749                                ber_int_t msgid)
750 {
751         struct smbldap_state *ldap_state = smbldap_find_state(ld);
752
753         return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid, 
754                                              ldap_state);
755 }
756 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
757 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
758
759 /*******************************************************************
760  connect to the ldap server under system privilege.
761 ******************************************************************/
762 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
763 {
764         int rc;
765         char *ldap_dn;
766         char *ldap_secret;
767
768         /* get the password */
769         if (!fetch_ldap_pw(&ldap_dn, &ldap_secret))
770         {
771                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
772                 return LDAP_INVALID_CREDENTIALS;
773         }
774
775         ldap_state->bind_dn = ldap_dn;
776         ldap_state->bind_secret = ldap_secret;
777
778         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
779            (OpenLDAP) doesnt' seem to support it */
780            
781         DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
782                   ldap_state->uri, ldap_dn));
783
784 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
785 # if LDAP_SET_REBIND_PROC_ARGS == 2     
786         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect); 
787 # endif
788 # if LDAP_SET_REBIND_PROC_ARGS == 3     
789         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);  
790 # endif
791 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
792 # if LDAP_SET_REBIND_PROC_ARGS == 2     
793         ldap_set_rebind_proc(ldap_struct, &rebindproc); 
794 # endif
795 # if LDAP_SET_REBIND_PROC_ARGS == 3     
796         ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);  
797 # endif
798 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
799
800         rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
801
802         if (rc != LDAP_SUCCESS) {
803                 char *ld_error = NULL;
804                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
805                                 &ld_error);
806                 DEBUG(ldap_state->num_failures ? 2 : 0,
807                       ("failed to bind to server with dn= %s Error: %s\n\t%s\n",
808                                ldap_dn ? ldap_dn : "(unknown)", ldap_err2string(rc),
809                                ld_error ? ld_error : "(unknown)"));
810                 SAFE_FREE(ld_error);
811                 ldap_state->num_failures++;
812                 return rc;
813         }
814
815         ldap_state->num_failures = 0;
816
817         DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
818         return rc;
819 }
820
821 /**********************************************************************
822 Connect to LDAP server (called before every ldap operation)
823 *********************************************************************/
824 static int smbldap_open(struct smbldap_state *ldap_state)
825 {
826         int rc;
827         SMB_ASSERT(ldap_state);
828                 
829 #ifndef NO_LDAP_SECURITY
830         if (geteuid() != 0) {
831                 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
832                 return  LDAP_INSUFFICIENT_ACCESS;
833         }
834 #endif
835
836         if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
837                 struct sockaddr_un addr;
838                 socklen_t len = sizeof(addr);
839                 int sd;
840                 if (ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd) == 0 &&
841                     getpeername(sd, (struct sockaddr *) &addr, &len) < 0) {
842                         /* the other end has died. reopen. */
843                         ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
844                         ldap_state->ldap_struct = NULL;
845                         ldap_state->last_ping = (time_t)0;
846                 } else {
847                         ldap_state->last_ping = time(NULL);
848                 } 
849         }
850
851         if (ldap_state->ldap_struct != NULL) {
852                 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
853                 return LDAP_SUCCESS;
854         }
855
856         if ((rc = smbldap_open_connection(ldap_state))) {
857                 return rc;
858         }
859
860         if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
861                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
862                 ldap_state->ldap_struct = NULL;
863                 return rc;
864         }
865
866
867         ldap_state->last_ping = time(NULL);
868         DEBUG(4,("The LDAP server is succesful connected\n"));
869
870         return LDAP_SUCCESS;
871 }
872
873 /**********************************************************************
874 Disconnect from LDAP server 
875 *********************************************************************/
876 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
877 {
878         if (!ldap_state)
879                 return NT_STATUS_INVALID_PARAMETER;
880                 
881         if (ldap_state->ldap_struct != NULL) {
882                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
883                 ldap_state->ldap_struct = NULL;
884         }
885
886         smbldap_delete_state(ldap_state);
887         
888         DEBUG(5,("The connection to the LDAP server was closed\n"));
889         /* maybe free the results here --metze */
890         
891         
892
893         return NT_STATUS_OK;
894 }
895
896 int smbldap_retry_open(struct smbldap_state *ldap_state, int *attempts)
897 {
898         int rc;
899
900         SMB_ASSERT(ldap_state && attempts);
901                 
902         if (*attempts != 0) {
903                 unsigned int sleep_time;
904                 uint8 rand_byte;
905
906                 /* Sleep for a random timeout */
907                 rand_byte = (char)(sys_random());
908
909                 sleep_time = (((*attempts)*(*attempts))/2)*rand_byte*2; 
910                 /* we retry after (0.5, 1, 2, 3, 4.5, 6) seconds
911                    on average.  
912                  */
913                 DEBUG(3, ("Sleeping for %u milliseconds before reconnecting\n", 
914                           sleep_time));
915                 smb_msleep(sleep_time);
916         }
917         (*attempts)++;
918
919         if ((rc = smbldap_open(ldap_state))) {
920                 DEBUG(1,("Connection to LDAP Server failed for the %d try!\n",*attempts));
921                 return rc;
922         } 
923         
924         return LDAP_SUCCESS;            
925 }
926
927
928 /*********************************************************************
929  ********************************************************************/
930
931 int smbldap_search(struct smbldap_state *ldap_state, 
932                    const char *base, int scope, const char *filter, 
933                    char *attrs[], int attrsonly, 
934                    LDAPMessage **res)
935 {
936         int             rc = LDAP_SERVER_DOWN;
937         int             attempts = 0;
938         char           *utf8_filter;
939
940         SMB_ASSERT(ldap_state);
941         
942         DEBUG(5,("smbldap_search: base => [%s], filter => [%s], scope => [%d]\n",
943                 base, filter, scope));
944
945         if (ldap_state->last_rebind.tv_sec > 0) {
946                 struct timeval  tval;
947                 int             tdiff = 0;
948                 int             sleep_time = 0;
949
950                 ZERO_STRUCT(tval);
951
952                 gettimeofday(&tval,NULL);
953
954                 tdiff = 1000000 *(tval.tv_sec - ldap_state->last_rebind.tv_sec) + 
955                         (tval.tv_usec - ldap_state->last_rebind.tv_usec);
956
957                 sleep_time = ((1000*lp_ldap_replication_sleep())-tdiff)/1000;
958
959                 if (sleep_time > 0) {
960                         /* we wait for the LDAP replication */
961                         DEBUG(5,("smbldap_search: waiting %d milliseconds for LDAP replication.\n",sleep_time));
962                         smb_msleep(sleep_time);
963                         DEBUG(5,("smbldap_search: go on!\n"));
964                         ZERO_STRUCT(ldap_state->last_rebind);
965                 }
966         }
967
968         if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
969                 return LDAP_NO_MEMORY;
970         }
971
972         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
973                 
974                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
975                         continue;
976                 
977                 rc = ldap_search_s(ldap_state->ldap_struct, base, scope, 
978                                    utf8_filter, attrs, attrsonly, res);
979         }
980         
981         if (rc == LDAP_SERVER_DOWN) {
982                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
983                 smbldap_close(ldap_state);      
984         }
985
986         ldap_state->last_use = time(NULL);
987
988         SAFE_FREE(utf8_filter);
989         return rc;
990 }
991
992 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
993 {
994         int             rc = LDAP_SERVER_DOWN;
995         int             attempts = 0;
996         char           *utf8_dn;
997
998         SMB_ASSERT(ldap_state);
999
1000         DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1001
1002         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1003                 return LDAP_NO_MEMORY;
1004         }
1005
1006         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1007                 
1008                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1009                         continue;
1010                 
1011                 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1012         }
1013         
1014         if (rc == LDAP_SERVER_DOWN) {
1015                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1016                 smbldap_close(ldap_state);      
1017         }
1018         
1019         ldap_state->last_use = time(NULL);
1020
1021         SAFE_FREE(utf8_dn);
1022         return rc;
1023 }
1024
1025 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1026 {
1027         int             rc = LDAP_SERVER_DOWN;
1028         int             attempts = 0;
1029         char           *utf8_dn;
1030         
1031         SMB_ASSERT(ldap_state);
1032
1033         DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1034
1035         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1036                 return LDAP_NO_MEMORY;
1037         }
1038
1039         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1040                 
1041                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1042                         continue;
1043                 
1044                 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1045         }
1046         
1047         if (rc == LDAP_SERVER_DOWN) {
1048                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1049                 smbldap_close(ldap_state);      
1050         }
1051                 
1052         ldap_state->last_use = time(NULL);
1053
1054         SAFE_FREE(utf8_dn);
1055         return rc;
1056 }
1057
1058 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1059 {
1060         int             rc = LDAP_SERVER_DOWN;
1061         int             attempts = 0;
1062         char           *utf8_dn;
1063         
1064         SMB_ASSERT(ldap_state);
1065
1066         DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1067
1068         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1069                 return LDAP_NO_MEMORY;
1070         }
1071
1072         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1073                 
1074                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1075                         continue;
1076                 
1077                 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1078         }
1079         
1080         if (rc == LDAP_SERVER_DOWN) {
1081                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1082                 smbldap_close(ldap_state);      
1083         }
1084                 
1085         ldap_state->last_use = time(NULL);
1086
1087         SAFE_FREE(utf8_dn);
1088         return rc;
1089 }
1090
1091 int smbldap_extended_operation(struct smbldap_state *ldap_state, 
1092                                LDAP_CONST char *reqoid, struct berval *reqdata, 
1093                                LDAPControl **serverctrls, LDAPControl **clientctrls, 
1094                                char **retoidp, struct berval **retdatap)
1095 {
1096         int             rc = LDAP_SERVER_DOWN;
1097         int             attempts = 0;
1098         
1099         if (!ldap_state)
1100                 return (-1);
1101
1102         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1103                 
1104                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1105                         continue;
1106                 
1107                 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid, reqdata, 
1108                                                serverctrls, clientctrls, retoidp, retdatap);
1109         }
1110         
1111         if (rc == LDAP_SERVER_DOWN) {
1112                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1113                 smbldap_close(ldap_state);      
1114         }
1115                 
1116         ldap_state->last_use = time(NULL);
1117
1118         return rc;
1119 }
1120
1121 /*******************************************************************
1122  run the search by name.
1123 ******************************************************************/
1124 int smbldap_search_suffix (struct smbldap_state *ldap_state, const char *filter, 
1125                            char **search_attr, LDAPMessage ** result)
1126 {
1127         int scope = LDAP_SCOPE_SUBTREE;
1128         int rc;
1129
1130         rc = smbldap_search(ldap_state, lp_ldap_suffix(), scope, filter, search_attr, 0, result);
1131
1132         if (rc != LDAP_SUCCESS) {
1133                 char *ld_error = NULL;
1134                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1135                                 &ld_error);
1136                 DEBUG(0,("smbldap_search_suffix: Problem during the LDAP search: %s (%s)\n", 
1137                         ld_error?ld_error:"(unknown)", ldap_err2string (rc)));
1138                 SAFE_FREE(ld_error);
1139         }
1140         
1141         return rc;
1142 }
1143
1144 static void smbldap_idle_fn(void **data, time_t *interval, time_t now)
1145 {
1146         struct smbldap_state *state = (struct smbldap_state *)(*data);
1147
1148         if (state->ldap_struct == NULL) {
1149                 DEBUG(10,("ldap connection not connected...\n"));
1150                 return;
1151         }
1152                 
1153         if ((state->last_use+SMBLDAP_IDLE_TIME) > now) {
1154                 DEBUG(10,("ldap connection not idle...\n"));
1155                 return;
1156         }
1157                 
1158         DEBUG(7,("ldap connection idle...closing connection\n"));
1159         smbldap_close(state);
1160 }
1161
1162 /**********************************************************************
1163  Housekeeping
1164  *********************************************************************/
1165
1166 void smbldap_free_struct(struct smbldap_state **ldap_state) 
1167 {
1168         smbldap_close(*ldap_state);
1169         
1170         if ((*ldap_state)->bind_secret) {
1171                 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1172         }
1173
1174         SAFE_FREE((*ldap_state)->bind_dn);
1175         SAFE_FREE((*ldap_state)->bind_secret);
1176
1177         smb_unregister_idle_event((*ldap_state)->event_id);
1178
1179         *ldap_state = NULL;
1180
1181         /* No need to free any further, as it is talloc()ed */
1182 }
1183
1184
1185 /**********************************************************************
1186  Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1187  *********************************************************************/
1188
1189 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state) 
1190 {
1191         *smbldap_state = talloc_zero(mem_ctx, sizeof(**smbldap_state));
1192         if (!*smbldap_state) {
1193                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1194                 return NT_STATUS_NO_MEMORY;
1195         }
1196
1197         if (location) {
1198                 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1199         } else {
1200                 (*smbldap_state)->uri = "ldap://localhost";
1201         }
1202
1203         (*smbldap_state)->event_id =
1204                 smb_register_idle_event(smbldap_idle_fn, (void *)(*smbldap_state),
1205                                         SMBLDAP_IDLE_TIME);
1206
1207         if ((*smbldap_state)->event_id == SMB_EVENT_ID_INVALID) {
1208                 DEBUG(0,("Failed to register LDAP idle event!\n"));
1209                 return NT_STATUS_INVALID_HANDLE;
1210         }
1211
1212         return NT_STATUS_OK;
1213 }
1214
1215 /*******************************************************************
1216  Return a copy of the DN for a LDAPMessage. Convert from utf8 to CH_UNIX.
1217 ********************************************************************/
1218
1219 char *smbldap_get_dn(LDAP *ld, LDAPMessage *entry)
1220 {
1221         char *utf8_dn, *unix_dn;
1222
1223         utf8_dn = ldap_get_dn(ld, entry);
1224         if (!utf8_dn) {
1225                 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1226                 return NULL;
1227         }
1228         if (pull_utf8_allocate(&unix_dn, utf8_dn) == (size_t)-1) {
1229                 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 [%s]\n", utf8_dn));
1230                 return NULL;
1231         }
1232         ldap_memfree(utf8_dn);
1233         return unix_dn;
1234 }