Fixes to check for wraps which could cause coredumps.
[samba.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_LIST_END,           NULL                    }
101 };
102
103 /* attributes used for alalocating RIDs */
104
105 ATTRIB_MAP_ENTRY dominfo_attr_list[] = {
106         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
107         { LDAP_ATTR_NEXT_RID,           "sambaNextRid"          },
108         { LDAP_ATTR_NEXT_USERRID,       "sambaNextUserRid"      },
109         { LDAP_ATTR_NEXT_GROUPRID,      "sambaNextGroupRid"     },
110         { LDAP_ATTR_DOM_SID,            LDAP_ATTRIBUTE_SID      },
111         { LDAP_ATTR_ALGORITHMIC_RID_BASE,"sambaAlgorithmicRidBase"},
112         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
113         { LDAP_ATTR_LIST_END,           NULL                    },
114 };
115
116 /* Samba 3.0 group mapping attributes */
117
118 ATTRIB_MAP_ENTRY groupmap_attr_list[] = {
119         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
120         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
121         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
122         { LDAP_ATTR_DESC,               "description"           },
123         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
124         { LDAP_ATTR_CN,                 "cn"                    },
125         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
126         { LDAP_ATTR_LIST_END,           NULL                    }       
127 };
128
129 ATTRIB_MAP_ENTRY groupmap_attr_list_to_delete[] = {
130         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
131         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
132         { LDAP_ATTR_DESC,               "description"           },
133         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
134         { LDAP_ATTR_LIST_END,           NULL                    }       
135 };
136
137 /* idmap_ldap sambaUnixIdPool */
138
139 ATTRIB_MAP_ENTRY idpool_attr_list[] = {
140         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
141         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
142         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
143         { LDAP_ATTR_LIST_END,           NULL                    }       
144 };
145
146 ATTRIB_MAP_ENTRY sidmap_attr_list[] = {
147         { LDAP_ATTR_SID,                LDAP_ATTRIBUTE_SID      },
148         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
149         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
150         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
151         { LDAP_ATTR_LIST_END,           NULL                    }       
152 };
153
154 /**********************************************************************
155  perform a simple table lookup and return the attribute name 
156  **********************************************************************/
157  
158  const char* get_attr_key2string( ATTRIB_MAP_ENTRY table[], int key )
159 {
160         int i = 0;
161         
162         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
163                 if ( table[i].attrib == key )
164                         return table[i].name;
165                 i++;
166         }
167         
168         return NULL;
169 }
170
171
172 /**********************************************************************
173  Return the list of attribute names from a mapping table
174  **********************************************************************/
175
176  char** get_attr_list( ATTRIB_MAP_ENTRY table[] )
177 {
178         char **names;
179         int i = 0;
180         
181         while ( table[i].attrib != LDAP_ATTR_LIST_END )
182                 i++;
183         i++;
184
185         names = (char**)malloc( sizeof(char*)*i );
186         if ( !names ) {
187                 DEBUG(0,("get_attr_list: out of memory\n"));
188                 return NULL;
189         }
190
191         i = 0;
192         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
193                 names[i] = strdup( table[i].name );
194                 i++;
195         }
196         names[i] = NULL;
197         
198         return names;
199 }
200
201 /*********************************************************************
202  Cleanup 
203  ********************************************************************/
204
205  void free_attr_list( char **list )
206 {
207         int i = 0;
208
209         if ( !list )
210                 return; 
211
212         while ( list[i] ) {
213                 SAFE_FREE( list[i] );
214                 i+=1;
215         }
216
217         SAFE_FREE( list );
218 }
219
220 /*******************************************************************
221  find the ldap password
222 ******************************************************************/
223 BOOL fetch_ldap_pw(char **dn, char** pw)
224 {
225         char *key = NULL;
226         size_t size;
227         
228         *dn = smb_xstrdup(lp_ldap_admin_dn());
229         
230         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, *dn) < 0) {
231                 SAFE_FREE(*dn);
232                 DEBUG(0, ("fetch_ldap_pw: asprintf failed!\n"));
233         }
234         
235         *pw=secrets_fetch(key, &size);
236         SAFE_FREE(key);
237
238         if (!size) {
239                 /* Upgrade 2.2 style entry */
240                 char *p;
241                 char* old_style_key = strdup(*dn);
242                 char *data;
243                 fstring old_style_pw;
244                 
245                 if (!old_style_key) {
246                         DEBUG(0, ("fetch_ldap_pw: strdup failed!\n"));
247                         return False;
248                 }
249
250                 for (p=old_style_key; *p; p++)
251                         if (*p == ',') *p = '/';
252         
253                 data=secrets_fetch(old_style_key, &size);
254                 if (!size && size < sizeof(old_style_pw)) {
255                         DEBUG(0,("fetch_ldap_pw: neither ldap secret retrieved!\n"));
256                         SAFE_FREE(old_style_key);
257                         SAFE_FREE(*dn);
258                         return False;
259                 }
260
261                 size = MIN(size, sizeof(fstring)-1);
262                 strncpy(old_style_pw, data, size);
263                 old_style_pw[size] = 0;
264
265                 SAFE_FREE(data);
266
267                 if (!secrets_store_ldap_pw(*dn, old_style_pw)) {
268                         DEBUG(0,("fetch_ldap_pw: ldap secret could not be upgraded!\n"));
269                         SAFE_FREE(old_style_key);
270                         SAFE_FREE(*dn);
271                         return False;                   
272                 }
273                 if (!secrets_delete(old_style_key)) {
274                         DEBUG(0,("fetch_ldap_pw: old ldap secret could not be deleted!\n"));
275                 }
276
277                 SAFE_FREE(old_style_key);
278
279                 *pw = smb_xstrdup(old_style_pw);                
280         }
281         
282         return True;
283 }
284
285 /*******************************************************************
286  Search an attribute and return the first value found.
287 ******************************************************************/
288
289  BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
290                                    const char *attribute, pstring value)
291 {
292         char **values;
293         
294         if ( !attribute )
295                 return False;
296                 
297         value[0] = '\0';
298
299         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
300                 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
301                 
302                 return False;
303         }
304         
305         if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, sizeof(pstring)) == (size_t)-1) {
306                 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n", 
307                           attribute, values[0]));
308                 ldap_value_free(values);
309                 return False;
310         }
311         
312         ldap_value_free(values);
313 #ifdef DEBUG_PASSWORDS
314         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
315 #endif  
316         return True;
317 }
318
319 /************************************************************************
320  Routine to manage the LDAPMod structure array
321  manage memory used by the array, by each struct, and values
322  ***********************************************************************/
323
324  void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
325 {
326         LDAPMod **mods;
327         int i;
328         int j;
329
330         mods = *modlist;
331
332         /* sanity checks on the mod values */
333
334         if (attribute == NULL || *attribute == '\0')
335                 return; 
336 #if 0   /* commented out after discussion with abartlet.  Do not reenable.
337            left here so other so re-add similar code   --jerry */
338         if (value == NULL || *value == '\0')
339                 return;
340 #endif
341
342         if (mods == NULL) 
343         {
344                 mods = (LDAPMod **) malloc(sizeof(LDAPMod *));
345                 if (mods == NULL)
346                 {
347                         DEBUG(0, ("make_a_mod: out of memory!\n"));
348                         return;
349                 }
350                 mods[0] = NULL;
351         }
352
353         for (i = 0; mods[i] != NULL; ++i) {
354                 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
355                         break;
356         }
357
358         if (mods[i] == NULL)
359         {
360                 mods = (LDAPMod **) Realloc (mods, (i + 2) * sizeof (LDAPMod *));
361                 if (mods == NULL)
362                 {
363                         DEBUG(0, ("make_a_mod: out of memory!\n"));
364                         return;
365                 }
366                 mods[i] = (LDAPMod *) malloc(sizeof(LDAPMod));
367                 if (mods[i] == NULL)
368                 {
369                         DEBUG(0, ("make_a_mod: out of memory!\n"));
370                         return;
371                 }
372                 mods[i]->mod_op = modop;
373                 mods[i]->mod_values = NULL;
374                 mods[i]->mod_type = strdup(attribute);
375                 mods[i + 1] = NULL;
376         }
377
378         if (value != NULL)
379         {
380                 char *utf8_value = NULL;
381
382                 j = 0;
383                 if (mods[i]->mod_values != NULL) {
384                         for (; mods[i]->mod_values[j] != NULL; j++);
385                 }
386                 mods[i]->mod_values = (char **)Realloc(mods[i]->mod_values,
387                                                (j + 2) * sizeof (char *));
388                                                
389                 if (mods[i]->mod_values == NULL) {
390                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
391                         return;
392                 }
393
394                 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
395                         DEBUG (0, ("make_a_mod: String conversion failure!\n"));
396                         return;
397                 }
398
399                 mods[i]->mod_values[j] = utf8_value;
400
401                 mods[i]->mod_values[j + 1] = NULL;
402         }
403         *modlist = mods;
404 }
405
406 /**********************************************************************
407   Set attribute to newval in LDAP, regardless of what value the
408   attribute had in LDAP before.
409 *********************************************************************/
410
411  void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
412                       LDAPMod ***mods,
413                       const char *attribute, const char *newval)
414 {
415         pstring oldval;
416         BOOL existed;
417
418         if (existing != NULL) {
419                 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval);
420         } else {
421                 existed = False;
422                 *oldval = '\0';
423         }
424
425         /* all of our string attributes are case insensitive */
426         
427         if (existed && (StrCaseCmp(oldval, newval) == 0)) {
428                 
429                 /* Believe it or not, but LDAP will deny a delete and
430                    an add at the same time if the values are the
431                    same... */
432                 return;
433         }
434
435         /* Regardless of the real operation (add or modify)
436            we add the new value here. We rely on deleting
437            the old value, should it exist. */
438
439         if ((newval != NULL) && (strlen(newval) > 0)) {
440                 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
441         }
442
443         if (!existed) {
444                 /* There has been no value before, so don't delete it.
445                    Here's a possible race: We might end up with
446                    duplicate attributes */
447                 return;
448         }
449
450         /* By deleting exactly the value we found in the entry this
451            should be race-free in the sense that the LDAP-Server will
452            deny the complete operation if somebody changed the
453            attribute behind our back. */
454
455         smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, oldval);
456 }
457
458 /**********************************************************************
459  Some varients of the LDAP rebind code do not pass in the third 'arg' 
460  pointer to a void*, so we try and work around it by assuming that the 
461  value of the 'LDAP *' pointer is the same as the one we had passed in
462  **********************************************************************/
463
464 struct smbldap_state_lookup {
465         LDAP *ld;
466         struct smbldap_state *smbldap_state;
467         struct smbldap_state_lookup *prev, *next;
468 };
469
470 static struct smbldap_state_lookup *smbldap_state_lookup_list;
471
472 static struct smbldap_state *smbldap_find_state(LDAP *ld) 
473 {
474         struct smbldap_state_lookup *t;
475
476         for (t = smbldap_state_lookup_list; t; t = t->next) {
477                 if (t->ld == ld) {
478                         return t->smbldap_state;
479                 }
480         }
481         return NULL;
482 }
483
484 static void smbldap_delete_state(struct smbldap_state *smbldap_state) 
485 {
486         struct smbldap_state_lookup *t;
487
488         for (t = smbldap_state_lookup_list; t; t = t->next) {
489                 if (t->smbldap_state == smbldap_state) {
490                         DLIST_REMOVE(smbldap_state_lookup_list, t);
491                         SAFE_FREE(t);
492                         return;
493                 }
494         }
495 }
496
497 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state) 
498 {
499         struct smbldap_state *tmp_ldap_state;
500         struct smbldap_state_lookup *t;
501         struct smbldap_state_lookup *tmp;
502         
503         if ((tmp_ldap_state = smbldap_find_state(ld))) {
504                 SMB_ASSERT(tmp_ldap_state == smbldap_state);
505                 return;
506         }
507
508         t = smb_xmalloc(sizeof(*t));
509         ZERO_STRUCTP(t);
510         
511         DLIST_ADD_END(smbldap_state_lookup_list, t, tmp);
512         t->ld = ld;
513         t->smbldap_state = smbldap_state;
514 }
515
516 /*******************************************************************
517  open a connection to the ldap server.
518 ******************************************************************/
519 static int smbldap_open_connection (struct smbldap_state *ldap_state)
520
521 {
522         int rc = LDAP_SUCCESS;
523         int version;
524         BOOL ldap_v3 = False;
525         LDAP **ldap_struct = &ldap_state->ldap_struct;
526
527 #ifdef HAVE_LDAP_INITIALIZE
528         DEBUG(10, ("smbldap_open_connection: %s\n", ldap_state->uri));
529         
530         if ((rc = ldap_initialize(ldap_struct, ldap_state->uri)) != LDAP_SUCCESS) {
531                 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
532                 return rc;
533         }
534 #else 
535
536         /* Parse the string manually */
537
538         {
539                 int port = 0;
540                 fstring protocol;
541                 fstring host;
542                 const char *p = ldap_state->uri; 
543                 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
544                 
545                 /* skip leading "URL:" (if any) */
546                 if ( strnequal( p, "URL:", 4 ) ) {
547                         p += 4;
548                 }
549                 
550                 sscanf(p, "%10[^:]://%254s[^:]:%d", protocol, host, &port);
551                 
552                 if (port == 0) {
553                         if (strequal(protocol, "ldap")) {
554                                 port = LDAP_PORT;
555                         } else if (strequal(protocol, "ldaps")) {
556                                 port = LDAPS_PORT;
557                         } else {
558                                 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
559                         }
560                 }
561                 
562                 if ((*ldap_struct = ldap_init(host, port)) == NULL)     {
563                         DEBUG(0, ("ldap_init failed !\n"));
564                         return LDAP_OPERATIONS_ERROR;
565                 }
566                 
567                 if (strequal(protocol, "ldaps")) {
568 #ifdef LDAP_OPT_X_TLS
569                         int tls = LDAP_OPT_X_TLS_HARD;
570                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
571                         {
572                                 DEBUG(0, ("Failed to setup a TLS session\n"));
573                         }
574                         
575                         DEBUG(3,("LDAPS option set...!\n"));
576 #else
577                         DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
578                         return LDAP_OPERATIONS_ERROR;
579 #endif
580                 }
581         }
582 #endif
583
584         /* Store the LDAP pointer in a lookup list */
585
586         smbldap_store_state(*ldap_struct, ldap_state);
587
588         /* Upgrade to LDAPv3 if possible */
589
590         if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
591         {
592                 if (version != LDAP_VERSION3)
593                 {
594                         version = LDAP_VERSION3;
595                         if (ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS) {
596                                 ldap_v3 = True;
597                         }
598                 } else {
599                         ldap_v3 = True;
600                 }
601         }
602
603         if (lp_ldap_ssl() == LDAP_SSL_START_TLS) {
604 #ifdef LDAP_OPT_X_TLS
605                 if (ldap_v3) {
606                         if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
607                         {
608                                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
609                                          ldap_err2string(rc)));
610                                 return rc;
611                         }
612                         DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
613                 } else {
614                         
615                         DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
616                         return LDAP_OPERATIONS_ERROR;
617                 }
618 #else
619                 DEBUG(0,("smbldap_open_connection: StartTLS not supported by LDAP client libraries!\n"));
620                 return LDAP_OPERATIONS_ERROR;
621 #endif
622         }
623
624         DEBUG(2, ("smbldap_open_connection: connection opened\n"));
625         return rc;
626 }
627
628
629 /*******************************************************************
630  a rebind function for authenticated referrals
631  This version takes a void* that we can shove useful stuff in :-)
632 ******************************************************************/
633 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
634 #else
635 static int rebindproc_with_state  (LDAP * ld, char **whop, char **credp, 
636                                    int *methodp, int freeit, void *arg)
637 {
638         struct smbldap_state *ldap_state = arg;
639         
640         /** @TODO Should we be doing something to check what servers we rebind to?
641             Could we get a referral to a machine that we don't want to give our
642             username and password to? */
643         
644         if (freeit) {
645                 SAFE_FREE(*whop);
646                 memset(*credp, '\0', strlen(*credp));
647                 SAFE_FREE(*credp);
648         } else {
649                 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n", 
650                           ldap_state->bind_dn));
651
652                 *whop = strdup(ldap_state->bind_dn);
653                 if (!*whop) {
654                         return LDAP_NO_MEMORY;
655                 }
656                 *credp = strdup(ldap_state->bind_secret);
657                 if (!*credp) {
658                         SAFE_FREE(*whop);
659                         return LDAP_NO_MEMORY;
660                 }
661                 *methodp = LDAP_AUTH_SIMPLE;
662         }
663         return 0;
664 }
665 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
666
667 /*******************************************************************
668  a rebind function for authenticated referrals
669  This version takes a void* that we can shove useful stuff in :-)
670  and actually does the connection.
671 ******************************************************************/
672 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
673 static int rebindproc_connect_with_state (LDAP *ldap_struct, 
674                                           LDAP_CONST char *url, 
675                                           ber_tag_t request,
676                                           ber_int_t msgid, void *arg)
677 {
678         struct smbldap_state *ldap_state = arg;
679         int rc;
680         DEBUG(5,("rebindproc_connect_with_state: Rebinding as \"%s\"\n", 
681                  ldap_state->bind_dn));
682         
683         /** @TODO Should we be doing something to check what servers we rebind to?
684             Could we get a referral to a machine that we don't want to give our
685             username and password to? */
686
687         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
688         
689         return rc;
690 }
691 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
692
693 /*******************************************************************
694  Add a rebind function for authenticated referrals
695 ******************************************************************/
696 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
697 #else
698 # if LDAP_SET_REBIND_PROC_ARGS == 2
699 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
700                        int *method, int freeit )
701 {
702         struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
703
704         return rebindproc_with_state(ldap_struct, whop, credp,
705                                      method, freeit, ldap_state);
706         
707 }
708 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
709 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
710
711 /*******************************************************************
712  a rebind function for authenticated referrals
713  this also does the connection, but no void*.
714 ******************************************************************/
715 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
716 # if LDAP_SET_REBIND_PROC_ARGS == 2
717 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
718                                ber_int_t msgid)
719 {
720         struct smbldap_state *ldap_state = smbldap_find_state(ld);
721
722         return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid, 
723                                              ldap_state);
724 }
725 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
726 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
727
728 /*******************************************************************
729  connect to the ldap server under system privilege.
730 ******************************************************************/
731 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
732 {
733         int rc;
734         char *ldap_dn;
735         char *ldap_secret;
736
737         /* get the password */
738         if (!fetch_ldap_pw(&ldap_dn, &ldap_secret))
739         {
740                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
741                 return LDAP_INVALID_CREDENTIALS;
742         }
743
744         ldap_state->bind_dn = ldap_dn;
745         ldap_state->bind_secret = ldap_secret;
746
747         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
748            (OpenLDAP) doesnt' seem to support it */
749            
750         DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
751                   ldap_state->uri, ldap_dn));
752
753 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
754 # if LDAP_SET_REBIND_PROC_ARGS == 2     
755         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect); 
756 # endif
757 # if LDAP_SET_REBIND_PROC_ARGS == 3     
758         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);  
759 # endif
760 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
761 # if LDAP_SET_REBIND_PROC_ARGS == 2     
762         ldap_set_rebind_proc(ldap_struct, &rebindproc); 
763 # endif
764 # if LDAP_SET_REBIND_PROC_ARGS == 3     
765         ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);  
766 # endif
767 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
768
769         rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
770
771         if (rc != LDAP_SUCCESS) {
772                 char *ld_error = NULL;
773                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
774                                 &ld_error);
775                 DEBUG(ldap_state->num_failures ? 2 : 0,
776                       ("failed to bind to server with dn= %s Error: %s\n\t%s\n",
777                                ldap_dn ? ldap_dn : "(unknown)", ldap_err2string(rc),
778                                ld_error ? ld_error : "(unknown)"));
779                 SAFE_FREE(ld_error);
780                 ldap_state->num_failures++;
781                 return rc;
782         }
783
784         ldap_state->num_failures = 0;
785
786         DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
787         return rc;
788 }
789
790 /**********************************************************************
791 Connect to LDAP server (called before every ldap operation)
792 *********************************************************************/
793 static int smbldap_open(struct smbldap_state *ldap_state)
794 {
795         int rc;
796         SMB_ASSERT(ldap_state);
797                 
798 #ifndef NO_LDAP_SECURITY
799         if (geteuid() != 0) {
800                 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
801                 return  LDAP_INSUFFICIENT_ACCESS;
802         }
803 #endif
804
805         if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
806                 struct sockaddr_un addr;
807                 socklen_t len = sizeof(addr);
808                 int sd;
809                 if (ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd) == 0 &&
810                     getpeername(sd, (struct sockaddr *) &addr, &len) < 0) {
811                         /* the other end has died. reopen. */
812                         ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
813                         ldap_state->ldap_struct = NULL;
814                         ldap_state->last_ping = (time_t)0;
815                 } else {
816                         ldap_state->last_ping = time(NULL);
817                 } 
818         }
819
820         if (ldap_state->ldap_struct != NULL) {
821                 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
822                 return LDAP_SUCCESS;
823         }
824
825         if ((rc = smbldap_open_connection(ldap_state))) {
826                 return rc;
827         }
828
829         if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
830                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
831                 ldap_state->ldap_struct = NULL;
832                 return rc;
833         }
834
835
836         ldap_state->last_ping = time(NULL);
837         DEBUG(4,("The LDAP server is succesful connected\n"));
838
839         return LDAP_SUCCESS;
840 }
841
842 /**********************************************************************
843 Disconnect from LDAP server 
844 *********************************************************************/
845 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
846 {
847         if (!ldap_state)
848                 return NT_STATUS_INVALID_PARAMETER;
849                 
850         if (ldap_state->ldap_struct != NULL) {
851                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
852                 ldap_state->ldap_struct = NULL;
853         }
854
855         smbldap_delete_state(ldap_state);
856         
857         DEBUG(5,("The connection to the LDAP server was closed\n"));
858         /* maybe free the results here --metze */
859         
860         
861
862         return NT_STATUS_OK;
863 }
864
865 int smbldap_retry_open(struct smbldap_state *ldap_state, int *attempts)
866 {
867         int rc;
868
869         SMB_ASSERT(ldap_state && attempts);
870                 
871         if (*attempts != 0) {
872                 unsigned int sleep_time;
873                 uint8 rand_byte;
874
875                 /* Sleep for a random timeout */
876                 rand_byte = (char)(sys_random());
877
878                 sleep_time = (((*attempts)*(*attempts))/2)*rand_byte*2; 
879                 /* we retry after (0.5, 1, 2, 3, 4.5, 6) seconds
880                    on average.  
881                  */
882                 DEBUG(3, ("Sleeping for %u milliseconds before reconnecting\n", 
883                           sleep_time));
884                 msleep(sleep_time);
885         }
886         (*attempts)++;
887
888         if ((rc = smbldap_open(ldap_state))) {
889                 DEBUG(1,("Connection to LDAP Server failed for the %d try!\n",*attempts));
890                 return rc;
891         } 
892         
893         return LDAP_SUCCESS;            
894 }
895
896
897 /*********************************************************************
898  ********************************************************************/
899
900 int smbldap_search(struct smbldap_state *ldap_state, 
901                    const char *base, int scope, const char *filter, 
902                    char *attrs[], int attrsonly, 
903                    LDAPMessage **res)
904 {
905         int             rc = LDAP_SERVER_DOWN;
906         int             attempts = 0;
907         char           *utf8_filter;
908
909         SMB_ASSERT(ldap_state);
910
911         if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
912                 return LDAP_NO_MEMORY;
913         }
914
915         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
916                 
917                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
918                         continue;
919                 
920                 rc = ldap_search_s(ldap_state->ldap_struct, base, scope, 
921                                    utf8_filter, attrs, attrsonly, res);
922         }
923         
924         if (rc == LDAP_SERVER_DOWN) {
925                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
926                 smbldap_close(ldap_state);      
927         }
928
929         ldap_state->last_use = time(NULL);
930
931         SAFE_FREE(utf8_filter);
932         return rc;
933 }
934
935 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
936 {
937         int             rc = LDAP_SERVER_DOWN;
938         int             attempts = 0;
939         char           *utf8_dn;
940
941         SMB_ASSERT(ldap_state);
942
943         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
944                 return LDAP_NO_MEMORY;
945         }
946
947         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
948                 
949                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
950                         continue;
951                 
952                 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
953         }
954         
955         if (rc == LDAP_SERVER_DOWN) {
956                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
957                 smbldap_close(ldap_state);      
958         }
959         
960         ldap_state->last_use = time(NULL);
961
962         SAFE_FREE(utf8_dn);
963         return rc;
964 }
965
966 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
967 {
968         int             rc = LDAP_SERVER_DOWN;
969         int             attempts = 0;
970         char           *utf8_dn;
971         
972         SMB_ASSERT(ldap_state);
973
974         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
975                 return LDAP_NO_MEMORY;
976         }
977
978         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
979                 
980                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
981                         continue;
982                 
983                 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
984         }
985         
986         if (rc == LDAP_SERVER_DOWN) {
987                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
988                 smbldap_close(ldap_state);      
989         }
990                 
991         ldap_state->last_use = time(NULL);
992
993         SAFE_FREE(utf8_dn);
994         return rc;
995 }
996
997 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
998 {
999         int             rc = LDAP_SERVER_DOWN;
1000         int             attempts = 0;
1001         char           *utf8_dn;
1002         
1003         SMB_ASSERT(ldap_state);
1004
1005         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1006                 return LDAP_NO_MEMORY;
1007         }
1008
1009         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1010                 
1011                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1012                         continue;
1013                 
1014                 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1015         }
1016         
1017         if (rc == LDAP_SERVER_DOWN) {
1018                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1019                 smbldap_close(ldap_state);      
1020         }
1021                 
1022         ldap_state->last_use = time(NULL);
1023
1024         SAFE_FREE(utf8_dn);
1025         return rc;
1026 }
1027
1028 int smbldap_extended_operation(struct smbldap_state *ldap_state, 
1029                                LDAP_CONST char *reqoid, struct berval *reqdata, 
1030                                LDAPControl **serverctrls, LDAPControl **clientctrls, 
1031                                char **retoidp, struct berval **retdatap)
1032 {
1033         int             rc = LDAP_SERVER_DOWN;
1034         int             attempts = 0;
1035         
1036         if (!ldap_state)
1037                 return (-1);
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_extended_operation_s(ldap_state->ldap_struct, reqoid, reqdata, 
1045                                                serverctrls, clientctrls, retoidp, retdatap);
1046         }
1047         
1048         if (rc == LDAP_SERVER_DOWN) {
1049                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1050                 smbldap_close(ldap_state);      
1051         }
1052                 
1053         ldap_state->last_use = time(NULL);
1054
1055         return rc;
1056 }
1057
1058 /*******************************************************************
1059  run the search by name.
1060 ******************************************************************/
1061 int smbldap_search_suffix (struct smbldap_state *ldap_state, const char *filter, 
1062                            char **search_attr, LDAPMessage ** result)
1063 {
1064         int scope = LDAP_SCOPE_SUBTREE;
1065         int rc;
1066
1067         DEBUG(2, ("smbldap_search_suffix: searching for:[%s]\n", filter));
1068
1069         rc = smbldap_search(ldap_state, lp_ldap_suffix(), scope, filter, search_attr, 0, result);
1070
1071         if (rc != LDAP_SUCCESS) {
1072                 char *ld_error = NULL;
1073                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1074                                 &ld_error);
1075                 DEBUG(0,("smbldap_search_suffix: Problem during the LDAP search: %s (%s)\n", 
1076                         ld_error?ld_error:"(unknown)", ldap_err2string (rc)));
1077                 DEBUG(3,("smbldap_search_suffix: Query was: %s, %s\n", lp_ldap_suffix(), 
1078                         filter));
1079                 SAFE_FREE(ld_error);
1080         }
1081         
1082         return rc;
1083 }
1084
1085 static void smbldap_idle_fn(void **data, time_t *interval, time_t now)
1086 {
1087         struct smbldap_state *state = (struct smbldap_state *)(*data);
1088
1089         if (state->ldap_struct == NULL) {
1090                 DEBUG(10,("ldap connection not connected...\n"));
1091                 return;
1092         }
1093                 
1094         if ((state->last_use+SMBLDAP_IDLE_TIME) > now) {
1095                 DEBUG(10,("ldap connection not idle...\n"));
1096                 return;
1097         }
1098                 
1099         DEBUG(7,("ldap connection idle...closing connection\n"));
1100         smbldap_close(state);
1101 }
1102
1103 /**********************************************************************
1104  Housekeeping
1105  *********************************************************************/
1106
1107 void smbldap_free_struct(struct smbldap_state **ldap_state) 
1108 {
1109         smbldap_close(*ldap_state);
1110         
1111         if ((*ldap_state)->bind_secret) {
1112                 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1113         }
1114
1115         SAFE_FREE((*ldap_state)->bind_dn);
1116         SAFE_FREE((*ldap_state)->bind_secret);
1117
1118         smb_unregister_idle_event((*ldap_state)->event_id);
1119
1120         *ldap_state = NULL;
1121
1122         /* No need to free any further, as it is talloc()ed */
1123 }
1124
1125
1126 /**********************************************************************
1127  Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1128  *********************************************************************/
1129
1130 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state) 
1131 {
1132         *smbldap_state = talloc_zero(mem_ctx, sizeof(**smbldap_state));
1133         if (!*smbldap_state) {
1134                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1135                 return NT_STATUS_NO_MEMORY;
1136         }
1137
1138         if (location) {
1139                 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1140         } else {
1141                 (*smbldap_state)->uri = "ldap://localhost";
1142         }
1143
1144         (*smbldap_state)->event_id =
1145                 smb_register_idle_event(smbldap_idle_fn, (void *)(*smbldap_state),
1146                                         SMBLDAP_IDLE_TIME);
1147
1148         if ((*smbldap_state)->event_id == SMB_EVENT_ID_INVALID) {
1149                 DEBUG(0,("Failed to register LDAP idle event!\n"));
1150                 return NT_STATUS_INVALID_HANDLE;
1151         }
1152
1153         return NT_STATUS_OK;
1154 }
1155
1156 /**********************************************************************
1157  Add the sambaDomain to LDAP, so we don't have to search for this stuff
1158  again.  This is a once-add operation for now.
1159
1160  TODO:  Add other attributes, and allow modification.
1161 *********************************************************************/
1162 static NTSTATUS add_new_domain_info(struct smbldap_state *ldap_state, 
1163                                     const char *domain_name) 
1164 {
1165         fstring sid_string;
1166         fstring algorithmic_rid_base_string;
1167         pstring filter, dn;
1168         LDAPMod **mods = NULL;
1169         int rc;
1170         int ldap_op;
1171         LDAPMessage *result = NULL;
1172         int num_result;
1173         char **attr_list;
1174         uid_t u_low, u_high;
1175         gid_t g_low, g_high;
1176         uint32 rid_low, rid_high;
1177
1178         slprintf (filter, sizeof (filter) - 1, "(&(%s=%s)(objectclass=%s))", 
1179                   get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1180                   domain_name, LDAP_OBJ_DOMINFO);
1181
1182         attr_list = get_attr_list( dominfo_attr_list );
1183         rc = smbldap_search_suffix(ldap_state, filter, attr_list, &result);
1184         free_attr_list( attr_list );
1185
1186         if (rc != LDAP_SUCCESS) {
1187                 return NT_STATUS_UNSUCCESSFUL;
1188         }
1189
1190         num_result = ldap_count_entries(ldap_state->ldap_struct, result);
1191         
1192         if (num_result > 1) {
1193                 DEBUG (0, ("More than domain with that name exists: bailing out!\n"));
1194                 ldap_msgfree(result);
1195                 return NT_STATUS_UNSUCCESSFUL;
1196         }
1197         
1198         /* Check if we need to add an entry */
1199         DEBUG(3,("Adding new domain\n"));
1200         ldap_op = LDAP_MOD_ADD;
1201
1202         pstr_sprintf(dn, "%s=%s,%s", get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN),
1203                 domain_name, lp_ldap_suffix());
1204
1205         /* Free original search */
1206         ldap_msgfree(result);
1207
1208         /* make the changes - the entry *must* not already have samba attributes */
1209         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1210                 domain_name);
1211
1212         /* If we don't have an entry, then ask secrets.tdb for what it thinks.  
1213            It may choose to make it up */
1214
1215         sid_to_string(sid_string, get_global_sam_sid());
1216         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOM_SID), sid_string);
1217
1218         slprintf(algorithmic_rid_base_string, sizeof(algorithmic_rid_base_string) - 1, "%i", algorithmic_rid_base());
1219         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_ALGORITHMIC_RID_BASE), 
1220                         algorithmic_rid_base_string);
1221         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_DOMINFO);
1222         
1223         /* add the sambaNext[User|Group]Rid attributes if the idmap ranges are set.
1224            TODO: fix all the places where the line between idmap and normal operations
1225            needed by smbd gets fuzzy   --jerry 2003-08-11                              */
1226         
1227         if ( lp_idmap_uid(&u_low, &u_high) && lp_idmap_gid(&g_low, &g_high)
1228                 && get_free_rid_range(&rid_low, &rid_high) ) 
1229         {
1230                 fstring rid_str;
1231                 
1232                 fstr_sprintf( rid_str, "%i", rid_high|USER_RID_TYPE );
1233                 DEBUG(10,("setting next available user rid [%s]\n", rid_str));
1234                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1235                         get_attr_key2string(dominfo_attr_list, LDAP_ATTR_NEXT_USERRID), 
1236                         rid_str);
1237                         
1238                 fstr_sprintf( rid_str, "%i", rid_high|GROUP_RID_TYPE );
1239                 DEBUG(10,("setting next available group rid [%s]\n", rid_str));
1240                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1241                         get_attr_key2string(dominfo_attr_list, LDAP_ATTR_NEXT_GROUPRID), 
1242                         rid_str);
1243                 
1244         }
1245
1246
1247         switch(ldap_op)
1248         {
1249         case LDAP_MOD_ADD: 
1250                 rc = smbldap_add(ldap_state, dn, mods);
1251                 break;
1252         case LDAP_MOD_REPLACE: 
1253                 rc = smbldap_modify(ldap_state, dn, mods);
1254                 break;
1255         default:        
1256                 DEBUG(0,("Wrong LDAP operation type: %d!\n", ldap_op));
1257                 return NT_STATUS_INVALID_PARAMETER;
1258         }
1259         
1260         if (rc!=LDAP_SUCCESS) {
1261                 char *ld_error = NULL;
1262                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
1263                 DEBUG(1,("failed to %s domain dn= %s with: %s\n\t%s\n",
1264                        ldap_op == LDAP_MOD_ADD ? "add" : "modify",
1265                        dn, ldap_err2string(rc),
1266                        ld_error?ld_error:"unknown"));
1267                 SAFE_FREE(ld_error);
1268
1269                 ldap_mods_free(mods, True);
1270                 return NT_STATUS_UNSUCCESSFUL;
1271         }
1272
1273         DEBUG(2,("added: domain = %s in the LDAP database\n", domain_name));
1274         ldap_mods_free(mods, True);
1275         return NT_STATUS_OK;
1276 }
1277
1278 /**********************************************************************
1279 Search for the domain info entry
1280 *********************************************************************/
1281 NTSTATUS smbldap_search_domain_info(struct smbldap_state *ldap_state,
1282                                     LDAPMessage ** result, const char *domain_name,
1283                                     BOOL try_add)
1284 {
1285         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1286         pstring filter;
1287         int rc;
1288         char **attr_list;
1289         int count;
1290
1291         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
1292                 LDAP_OBJ_DOMINFO,
1293                 get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1294                 domain_name);
1295
1296         DEBUG(2, ("Searching for:[%s]\n", filter));
1297
1298
1299         attr_list = get_attr_list( dominfo_attr_list );
1300         rc = smbldap_search_suffix(ldap_state, filter, attr_list , result);
1301         free_attr_list( attr_list );
1302
1303         if (rc != LDAP_SUCCESS) {
1304                 DEBUG(2,("Problem during LDAPsearch: %s\n", ldap_err2string (rc)));
1305                 DEBUG(2,("Query was: %s, %s\n", lp_ldap_suffix(), filter));
1306         } else if (ldap_count_entries(ldap_state->ldap_struct, *result) < 1) {
1307                 DEBUG(3, ("Got no domain info entries for domain\n"));
1308                 ldap_msgfree(*result);
1309                 *result = NULL;
1310                 if (try_add && NT_STATUS_IS_OK(ret = add_new_domain_info(ldap_state, domain_name))) {
1311                         return smbldap_search_domain_info(ldap_state, result, domain_name, False);
1312                 } 
1313                 else {
1314                         DEBUG(0, ("Adding domain info for %s failed with %s\n", 
1315                                 domain_name, nt_errstr(ret)));
1316                         return ret;
1317                 }
1318         } else if ((count = ldap_count_entries(ldap_state->ldap_struct, *result)) > 1) {
1319                 DEBUG(0, ("Got too many (%d) domain info entries for domain %s\n",
1320                           count, domain_name));
1321                 ldap_msgfree(*result);
1322                 *result = NULL;
1323                 return ret;
1324         } else {
1325                 return NT_STATUS_OK;
1326         }
1327         
1328         return ret;
1329 }
1330
1331 /*******************************************************************
1332  Return a copy of the DN for a LDAPMessage. Convert from utf8 to CH_UNIX.
1333 ********************************************************************/
1334
1335 char *smbldap_get_dn(LDAP *ld, LDAPMessage *entry)
1336 {
1337         char *utf8_dn, *unix_dn;
1338
1339         utf8_dn = ldap_get_dn(ld, entry);
1340         if (!utf8_dn) {
1341                 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1342                 return NULL;
1343         }
1344         if (pull_utf8_allocate((void **) &unix_dn, utf8_dn) == (size_t)-1) {
1345                 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 [%s]\n", utf8_dn));
1346                 return NULL;
1347         }
1348         ldap_memfree(utf8_dn);
1349         return unix_dn;
1350 }