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