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