r4088: Get medieval on our ass about malloc.... :-). Take control of all our allocation
[bbaumbach/samba-autobuild/.git] / source3 / nsswitch / winbindd_util.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon for ntdom nss module
5
6    Copyright (C) Tim Potter 2000-2001
7    Copyright (C) 2001 by Martin Pool <mbp@samba.org>
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25 #include "winbindd.h"
26
27 #undef DBGC_CLASS
28 #define DBGC_CLASS DBGC_WINBIND
29
30 /**
31  * @file winbindd_util.c
32  *
33  * Winbind daemon for NT domain authentication nss module.
34  **/
35
36
37 /**
38  * Used to clobber name fields that have an undefined value.
39  *
40  * Correct code should never look at a field that has this value.
41  **/
42
43 static const fstring name_deadbeef = "<deadbeef>";
44
45 /* The list of trusted domains.  Note that the list can be deleted and
46    recreated using the init_domain_list() function so pointers to
47    individual winbindd_domain structures cannot be made.  Keep a copy of
48    the domain name instead. */
49
50 static struct winbindd_domain *_domain_list;
51
52 /**
53    When was the last scan of trusted domains done?
54    
55    0 == not ever
56 */
57
58 static time_t last_trustdom_scan;
59
60 struct winbindd_domain *domain_list(void)
61 {
62         /* Initialise list */
63
64         if (!_domain_list) 
65                 if (!init_domain_list()) 
66                         return NULL;
67
68         return _domain_list;
69 }
70
71 /* Free all entries in the trusted domain list */
72
73 void free_domain_list(void)
74 {
75         struct winbindd_domain *domain = _domain_list;
76
77         while(domain) {
78                 struct winbindd_domain *next = domain->next;
79                 
80                 DLIST_REMOVE(_domain_list, domain);
81                 SAFE_FREE(domain);
82                 domain = next;
83         }
84 }
85
86 static BOOL is_internal_domain(const DOM_SID *sid)
87 {
88         extern DOM_SID global_sid_Builtin;
89
90         if (sid == NULL)
91                 return False;
92
93         if (sid_compare_domain(sid, get_global_sam_sid()) == 0)
94                 return True;
95
96         if (sid_compare_domain(sid, &global_sid_Builtin) == 0)
97                 return True;
98
99         return False;
100 }
101
102
103 /* Add a trusted domain to our list of domains */
104 static struct winbindd_domain *add_trusted_domain(const char *domain_name, const char *alt_name,
105                                                   struct winbindd_methods *methods,
106                                                   DOM_SID *sid)
107 {
108         struct winbindd_domain *domain;
109         const char *alternative_name = NULL;
110         static const DOM_SID null_sid;
111         
112         /* ignore alt_name if we are not in an AD domain */
113         
114         if ( (lp_security() == SEC_ADS) && alt_name && *alt_name) {
115                 alternative_name = alt_name;
116         }
117         
118         /* We can't call domain_list() as this function is called from
119            init_domain_list() and we'll get stuck in a loop. */
120         for (domain = _domain_list; domain; domain = domain->next) {
121                 if (strequal(domain_name, domain->name) ||
122                     strequal(domain_name, domain->alt_name)) {
123                         return domain;
124                 }
125                 if (alternative_name && *alternative_name) {
126                         if (strequal(alternative_name, domain->name) ||
127                             strequal(alternative_name, domain->alt_name)) {
128                                 return domain;
129                         }
130                 }
131                 if (sid) {
132                         if (sid_equal(sid, &null_sid) ) {
133                                 
134                         } else if (sid_equal(sid, &domain->sid)) {
135                                 return domain;
136                         }
137                 }
138         }
139         
140         /* Create new domain entry */
141
142         if ((domain = SMB_MALLOC_P(struct winbindd_domain)) == NULL)
143                 return NULL;
144
145         /* Fill in fields */
146         
147         ZERO_STRUCTP(domain);
148
149         /* prioritise the short name */
150         if (strchr_m(domain_name, '.') && alternative_name && *alternative_name) {
151                 fstrcpy(domain->name, alternative_name);
152                 fstrcpy(domain->alt_name, domain_name);
153         } else {
154                 fstrcpy(domain->name, domain_name);
155                 if (alternative_name) {
156                         fstrcpy(domain->alt_name, alternative_name);
157                 }
158         }
159
160         domain->methods = methods;
161         domain->backend = NULL;
162         domain->internal = is_internal_domain(sid);
163         domain->sequence_number = DOM_SEQUENCE_NONE;
164         domain->last_seq_check = 0;
165         domain->initialized = False;
166         if (sid) {
167                 sid_copy(&domain->sid, sid);
168         }
169         
170         DEBUG(3,("add_trusted_domain: %s is an %s %s domain\n", domain->name,
171                  domain->active_directory ? "ADS" : "NT4", 
172                  domain->native_mode ? "native mode" : 
173                  ((domain->active_directory && !domain->native_mode) ? "mixed mode" : "")));
174
175         /* Link to domain list */
176         DLIST_ADD(_domain_list, domain);
177         
178         DEBUG(2,("Added domain %s %s %s\n", 
179                  domain->name, domain->alt_name,
180                  &domain->sid?sid_string_static(&domain->sid):""));
181         
182         return domain;
183 }
184
185 /********************************************************************
186   rescan our domains looking for new trusted domains
187 ********************************************************************/
188
189 static void add_trusted_domains( struct winbindd_domain *domain )
190 {
191         extern struct winbindd_methods cache_methods;
192         TALLOC_CTX *mem_ctx;
193         NTSTATUS result;
194         time_t t;
195         char **names;
196         char **alt_names;
197         int num_domains = 0;
198         DOM_SID *dom_sids, null_sid;
199         int i;
200         struct winbindd_domain *new_domain;
201
202         /* trusted domains might be disabled */
203         if (!lp_allow_trusted_domains()) {
204                 return;
205         }
206
207         DEBUG(5, ("scanning trusted domain list\n"));
208
209         if (!(mem_ctx = talloc_init("init_domain_list")))
210                 return;
211            
212         ZERO_STRUCTP(&null_sid);
213
214         t = time(NULL);
215         
216         /* ask the DC what domains it trusts */
217         
218         result = domain->methods->trusted_domains(domain, mem_ctx, (unsigned int *)&num_domains,
219                 &names, &alt_names, &dom_sids);
220                 
221         if ( NT_STATUS_IS_OK(result) ) {
222
223                 /* Add each domain to the trusted domain list */
224                 
225                 for(i = 0; i < num_domains; i++) {
226                         DEBUG(10,("Found domain %s\n", names[i]));
227                         add_trusted_domain(names[i], alt_names?alt_names[i]:NULL,
228                                            &cache_methods, &dom_sids[i]);
229                                            
230                         /* if the SID was empty, we better set it now */
231                         
232                         if ( sid_equal(&dom_sids[i], &null_sid) ) {
233                         
234                                 new_domain = find_domain_from_name(names[i]);
235                                  
236                                 /* this should never happen */
237                                 if ( !new_domain ) {    
238                                         DEBUG(0,("rescan_trust_domains: can't find the domain I just added! [%s]\n",
239                                                 names[i]));
240                                         break;
241                                 }
242                                  
243                                 /* call the cache method; which will operate on the winbindd_domain \
244                                    passed in and choose either rpc or ads as appropriate */
245
246                                 result = domain->methods->domain_sid( new_domain, &new_domain->sid );
247                                  
248                                 if ( NT_STATUS_IS_OK(result) )
249                                         sid_copy( &dom_sids[i], &new_domain->sid );
250                         }
251                         
252                         /* store trusted domain in the cache */
253                         trustdom_cache_store(names[i], alt_names ? alt_names[i] : NULL,
254                                              &dom_sids[i], t + WINBINDD_RESCAN_FREQ);
255                 }
256         }
257
258         talloc_destroy(mem_ctx);
259 }
260
261 /********************************************************************
262  Periodically we need to refresh the trusted domain cache for smbd 
263 ********************************************************************/
264
265 void rescan_trusted_domains( void )
266 {
267         time_t now = time(NULL);
268         struct winbindd_domain *mydomain = NULL;
269         
270         /* see if the time has come... */
271         
272         if ( (now > last_trustdom_scan) && ((now-last_trustdom_scan) < WINBINDD_RESCAN_FREQ) )
273                 return;
274                 
275         if ( (mydomain = find_our_domain()) == NULL ) {
276                 DEBUG(0,("rescan_trusted_domains: Can't find my own domain!\n"));
277                 return;
278         }
279         
280         /* this will only add new domains we didn't already know about */
281         
282         add_trusted_domains( mydomain );
283
284         last_trustdom_scan = now;
285         
286         return; 
287 }
288
289 /* Look up global info for the winbind daemon */
290 BOOL init_domain_list(void)
291 {
292         extern DOM_SID global_sid_Builtin;
293         extern struct winbindd_methods cache_methods;
294         extern struct winbindd_methods passdb_methods;
295         struct winbindd_domain *domain;
296
297         /* Free existing list */
298         free_domain_list();
299
300         /* Add ourselves as the first entry. */
301
302         if (IS_DC) {
303                 domain = add_trusted_domain(get_global_sam_name(), NULL,
304                                             &passdb_methods, get_global_sam_sid());
305         } else {
306         
307                 domain = add_trusted_domain( lp_workgroup(), lp_realm(),
308                                              &cache_methods, NULL);
309         
310                 /* set flags about native_mode, active_directory */
311                 set_dc_type_and_flags(domain);
312         }
313
314         domain->primary = True;
315
316         /* get any alternate name for the primary domain */
317         
318         cache_methods.alternate_name(domain);
319         
320         /* now we have the correct netbios (short) domain name */
321         
322         if ( *domain->name )
323                 set_global_myworkgroup( domain->name );
324                 
325         if (!secrets_fetch_domain_sid(domain->name, &domain->sid)) {
326                 DEBUG(1, ("Could not fetch sid for our domain %s\n",
327                           domain->name));
328                 return False;
329         }
330
331         /* do an initial scan for trusted domains */
332         add_trusted_domains(domain);
333
334
335         /* Add our local SAM domains */
336
337         add_trusted_domain("BUILTIN", NULL, &passdb_methods,
338                            &global_sid_Builtin);
339
340         if (!IS_DC) {
341                 add_trusted_domain(get_global_sam_name(), NULL,
342                                    &passdb_methods, get_global_sam_sid());
343         }
344         
345         /* avoid rescanning this right away */
346         last_trustdom_scan = time(NULL);
347         return True;
348 }
349
350 /** 
351  * Given a domain name, return the struct winbindd domain info for it 
352  *
353  * @note Do *not* pass lp_workgroup() to this function.  domain_list
354  *       may modify it's value, and free that pointer.  Instead, our local
355  *       domain may be found by calling find_our_domain().
356  *       directly.
357  *
358  *
359  * @return The domain structure for the named domain, if it is working.
360  */
361
362 struct winbindd_domain *find_domain_from_name(const char *domain_name)
363 {
364         struct winbindd_domain *domain;
365
366         /* Search through list */
367
368         for (domain = domain_list(); domain != NULL; domain = domain->next) {
369                 if (strequal(domain_name, domain->name) ||
370                     (domain->alt_name[0] && strequal(domain_name, domain->alt_name))) {
371                         if (!domain->initialized)
372                                 set_dc_type_and_flags(domain);
373
374                         return domain;
375                 }
376         }
377
378         /* Not found */
379
380         return NULL;
381 }
382
383 /* Given a domain sid, return the struct winbindd domain info for it */
384
385 struct winbindd_domain *find_domain_from_sid(const DOM_SID *sid)
386 {
387         struct winbindd_domain *domain;
388
389         /* Search through list */
390
391         for (domain = domain_list(); domain != NULL; domain = domain->next) {
392                 if (sid_compare_domain(sid, &domain->sid) == 0) {
393                         if (!domain->initialized)
394                                 set_dc_type_and_flags(domain);
395                         return domain;
396                 }
397         }
398
399         /* Not found */
400
401         return NULL;
402 }
403
404 /* Given a domain sid, return the struct winbindd domain info for it */
405
406 struct winbindd_domain *find_our_domain(void)
407 {
408         struct winbindd_domain *domain;
409
410         /* Search through list */
411
412         for (domain = domain_list(); domain != NULL; domain = domain->next) {
413                 if (domain->primary)
414                         return domain;
415         }
416
417         /* Not found */
418
419         return NULL;
420 }
421
422 /* Find the appropriate domain to lookup a name or SID */
423
424 struct winbindd_domain *find_lookup_domain_from_sid(const DOM_SID *sid)
425 {
426         /* A DC can't ask the local smbd for remote SIDs, here winbindd is the
427          * one to contact the external DC's. On member servers the internal
428          * domains are different: These are part of the local SAM. */
429
430         if (IS_DC || is_internal_domain(sid))
431                 return find_domain_from_sid(sid);
432
433         /* On a member server a query for SID or name can always go to our
434          * primary DC. */
435
436         return find_our_domain();
437 }
438
439 struct winbindd_domain *find_lookup_domain_from_name(const char *domain_name)
440 {
441         if (IS_DC || strequal(domain_name, "BUILTIN") ||
442             strequal(domain_name, get_global_sam_name()))
443                 return find_domain_from_name(domain_name);
444
445         return find_our_domain();
446 }
447
448 /* Lookup a sid in a domain from a name */
449
450 BOOL winbindd_lookup_sid_by_name(struct winbindd_domain *domain, 
451                                  const char *domain_name,
452                                  const char *name, DOM_SID *sid, 
453                                  enum SID_NAME_USE *type)
454 {
455         NTSTATUS result;
456         TALLOC_CTX *mem_ctx;
457
458         mem_ctx = talloc_init("lookup_sid_by_name for %s\\%s\n",
459                               domain_name, name);
460         if (!mem_ctx) 
461                 return False;
462         
463         /* Lookup name */
464         result = domain->methods->name_to_sid(domain, mem_ctx, domain_name, name, sid, type);
465
466         talloc_destroy(mem_ctx);
467         
468         /* Return rid and type if lookup successful */
469         if (!NT_STATUS_IS_OK(result)) {
470                 *type = SID_NAME_UNKNOWN;
471         }
472
473         return NT_STATUS_IS_OK(result);
474 }
475
476 /**
477  * @brief Lookup a name in a domain from a sid.
478  *
479  * @param sid Security ID you want to look up.
480  * @param name On success, set to the name corresponding to @p sid.
481  * @param dom_name On success, set to the 'domain name' corresponding to @p sid.
482  * @param type On success, contains the type of name: alias, group or
483  * user.
484  * @retval True if the name exists, in which case @p name and @p type
485  * are set, otherwise False.
486  **/
487 BOOL winbindd_lookup_name_by_sid(DOM_SID *sid,
488                                  fstring dom_name,
489                                  fstring name,
490                                  enum SID_NAME_USE *type)
491 {
492         char *names;
493         char *dom_names;
494         NTSTATUS result;
495         TALLOC_CTX *mem_ctx;
496         BOOL rv = False;
497         struct winbindd_domain *domain;
498
499         domain = find_lookup_domain_from_sid(sid);
500
501         if (!domain) {
502                 DEBUG(1,("Can't find domain from sid\n"));
503                 return False;
504         }
505
506         /* Lookup name */
507
508         if (!(mem_ctx = talloc_init("winbindd_lookup_name_by_sid")))
509                 return False;
510         
511         result = domain->methods->sid_to_name(domain, mem_ctx, sid, &dom_names, &names, type);
512
513         /* Return name and type if successful */
514         
515         if ((rv = NT_STATUS_IS_OK(result))) {
516                 fstrcpy(dom_name, dom_names);
517                 fstrcpy(name, names);
518         } else {
519                 *type = SID_NAME_UNKNOWN;
520                 fstrcpy(name, name_deadbeef);
521         }
522         
523         talloc_destroy(mem_ctx);
524
525         return rv;
526 }
527
528
529 /* Free state information held for {set,get,end}{pw,gr}ent() functions */
530
531 void free_getent_state(struct getent_state *state)
532 {
533         struct getent_state *temp;
534
535         /* Iterate over state list */
536
537         temp = state;
538
539         while(temp != NULL) {
540                 struct getent_state *next;
541
542                 /* Free sam entries then list entry */
543
544                 SAFE_FREE(state->sam_entries);
545                 DLIST_REMOVE(state, state);
546                 next = temp->next;
547
548                 SAFE_FREE(temp);
549                 temp = next;
550         }
551 }
552
553 /* Parse winbindd related parameters */
554
555 BOOL winbindd_param_init(void)
556 {
557         /* Parse winbind uid and winbind_gid parameters */
558
559         if (!lp_idmap_uid(&server_state.uid_low, &server_state.uid_high)) {
560                 DEBUG(0, ("winbindd: idmap uid range missing or invalid\n"));
561                 DEBUG(0, ("winbindd: cannot continue, exiting.\n"));
562                 return False;
563         }
564         
565         if (!lp_idmap_gid(&server_state.gid_low, &server_state.gid_high)) {
566                 DEBUG(0, ("winbindd: idmap gid range missing or invalid\n"));
567                 DEBUG(0, ("winbindd: cannot continue, exiting.\n"));
568                 return False;
569         }
570         
571         return True;
572 }
573
574 /* Check if a domain is present in a comma-separated list of domains */
575
576 BOOL check_domain_env(char *domain_env, char *domain)
577 {
578         fstring name;
579         const char *tmp = domain_env;
580
581         while(next_token(&tmp, name, ",", sizeof(fstring))) {
582                 if (strequal(name, domain))
583                         return True;
584         }
585
586         return False;
587 }
588
589 /* Is this a domain which we may assume no DOMAIN\ prefix? */
590
591 static BOOL assume_domain(const char *domain) {
592         if ((lp_winbind_use_default_domain()  
593                   || lp_winbind_trusted_domains_only()) &&
594             strequal(lp_workgroup(), domain)) 
595                 return True;
596
597         if (strequal(get_global_sam_name(), domain)) 
598                 return True;
599         
600         return False;
601 }
602
603 /* Parse a string of the form DOMAIN/user into a domain and a user */
604
605 BOOL parse_domain_user(const char *domuser, fstring domain, fstring user)
606 {
607         char *p = strchr(domuser,*lp_winbind_separator());
608
609         if ( !p ) {
610                 fstrcpy(user, domuser);
611                 
612                 if ( assume_domain(lp_workgroup())) {
613                         fstrcpy(domain, lp_workgroup());
614                 } else {
615                         fstrcpy( domain, get_global_sam_name() ); 
616                 }
617         } 
618         else {
619                 fstrcpy(user, p+1);
620                 fstrcpy(domain, domuser);
621                 domain[PTR_DIFF(p, domuser)] = 0;
622         }
623         
624         strupper_m(domain);
625         
626         return True;
627 }
628
629 /*
630     Fill DOMAIN\\USERNAME entry accounting 'winbind use default domain' and
631     'winbind separator' options.
632     This means:
633         - omit DOMAIN when 'winbind use default domain = true' and DOMAIN is
634         lp_workgroup()
635
636     If we are a PDC or BDC, and this is for our domain, do likewise.
637
638     Also, if omit DOMAIN if 'winbind trusted domains only = true', as the 
639     username is then unqualified in unix
640          
641 */
642 void fill_domain_username(fstring name, const char *domain, const char *user)
643 {
644         strlower_m( name );
645
646         if (assume_domain(domain)) {
647                 strlcpy(name, user, sizeof(fstring));
648         } else {
649                 slprintf(name, sizeof(fstring) - 1, "%s%c%s",
650                          domain, *lp_winbind_separator(),
651                          user);
652         }
653 }
654
655 /*
656  * Winbindd socket accessor functions
657  */
658
659 char *get_winbind_priv_pipe_dir(void) 
660 {
661         return lock_path(WINBINDD_PRIV_SOCKET_SUBDIR);
662 }
663
664 /* Open the winbindd socket */
665
666 static int _winbindd_socket = -1;
667 static int _winbindd_priv_socket = -1;
668
669 int open_winbindd_socket(void)
670 {
671         if (_winbindd_socket == -1) {
672                 _winbindd_socket = create_pipe_sock(
673                         WINBINDD_SOCKET_DIR, WINBINDD_SOCKET_NAME, 0755);
674                 DEBUG(10, ("open_winbindd_socket: opened socket fd %d\n",
675                            _winbindd_socket));
676         }
677
678         return _winbindd_socket;
679 }
680
681 int open_winbindd_priv_socket(void)
682 {
683         if (_winbindd_priv_socket == -1) {
684                 _winbindd_priv_socket = create_pipe_sock(
685                         get_winbind_priv_pipe_dir(), WINBINDD_SOCKET_NAME, 0750);
686                 DEBUG(10, ("open_winbindd_priv_socket: opened socket fd %d\n",
687                            _winbindd_priv_socket));
688         }
689
690         return _winbindd_priv_socket;
691 }
692
693 /* Close the winbindd socket */
694
695 void close_winbindd_socket(void)
696 {
697         if (_winbindd_socket != -1) {
698                 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
699                            _winbindd_socket));
700                 close(_winbindd_socket);
701                 _winbindd_socket = -1;
702         }
703         if (_winbindd_priv_socket != -1) {
704                 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
705                            _winbindd_priv_socket));
706                 close(_winbindd_priv_socket);
707                 _winbindd_priv_socket = -1;
708         }
709 }
710
711 /*
712  * Client list accessor functions
713  */
714
715 static struct winbindd_cli_state *_client_list;
716 static int _num_clients;
717
718 /* Return list of all connected clients */
719
720 struct winbindd_cli_state *winbindd_client_list(void)
721 {
722         return _client_list;
723 }
724
725 /* Add a connection to the list */
726
727 void winbindd_add_client(struct winbindd_cli_state *cli)
728 {
729         DLIST_ADD(_client_list, cli);
730         _num_clients++;
731 }
732
733 /* Remove a client from the list */
734
735 void winbindd_remove_client(struct winbindd_cli_state *cli)
736 {
737         DLIST_REMOVE(_client_list, cli);
738         _num_clients--;
739 }
740
741 /* Demote a client to be the last in the list */
742
743 void winbindd_demote_client(struct winbindd_cli_state *cli)
744 {
745         struct winbindd_cli_state *tmp;
746         DLIST_DEMOTE(_client_list, cli, tmp);
747 }
748
749 /* Close all open clients */
750
751 void winbindd_kill_all_clients(void)
752 {
753         struct winbindd_cli_state *cl = winbindd_client_list();
754
755         DEBUG(10, ("winbindd_kill_all_clients: going postal\n"));
756
757         while (cl) {
758                 struct winbindd_cli_state *next;
759                 
760                 next = cl->next;
761                 winbindd_remove_client(cl);
762                 cl = next;
763         }
764 }
765
766 /* Return number of open clients */
767
768 int winbindd_num_clients(void)
769 {
770         return _num_clients;
771 }
772
773 /* Help with RID -> SID conversion */
774
775 DOM_SID *rid_to_talloced_sid(struct winbindd_domain *domain,
776                                     TALLOC_CTX *mem_ctx,
777                                     uint32 rid) 
778 {
779         DOM_SID *sid;
780         sid = TALLOC_P(mem_ctx, DOM_SID);
781         if (!sid) {
782                 smb_panic("rid_to_to_talloced_sid: talloc for DOM_SID failed!\n");
783         }
784         sid_copy(sid, &domain->sid);
785         sid_append_rid(sid, rid);
786         return sid;
787 }
788         
789 /*****************************************************************************
790  For idmap conversion: convert one record to new format
791  Ancient versions (eg 2.2.3a) of winbindd_idmap.tdb mapped DOMAINNAME/rid
792  instead of the SID.
793 *****************************************************************************/
794 static int convert_fn(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA data, void *state)
795 {
796         struct winbindd_domain *domain;
797         char *p;
798         DOM_SID sid;
799         uint32 rid;
800         fstring keystr;
801         fstring dom_name;
802         TDB_DATA key2;
803         BOOL *failed = (BOOL *)state;
804
805         DEBUG(10,("Converting %s\n", key.dptr));
806
807         p = strchr(key.dptr, '/');
808         if (!p)
809                 return 0;
810
811         *p = 0;
812         fstrcpy(dom_name, key.dptr);
813         *p++ = '/';
814
815         domain = find_domain_from_name(dom_name);
816         if (domain == NULL) {
817                 /* We must delete the old record. */
818                 DEBUG(0,("Unable to find domain %s\n", dom_name ));
819                 DEBUG(0,("deleting record %s\n", key.dptr ));
820
821                 if (tdb_delete(tdb, key) != 0) {
822                         DEBUG(0, ("Unable to delete record %s\n", key.dptr));
823                         *failed = True;
824                         return -1;
825                 }
826
827                 return 0;
828         }
829
830         rid = atoi(p);
831
832         sid_copy(&sid, &domain->sid);
833         sid_append_rid(&sid, rid);
834
835         sid_to_string(keystr, &sid);
836         key2.dptr = keystr;
837         key2.dsize = strlen(keystr) + 1;
838
839         if (tdb_store(tdb, key2, data, TDB_INSERT) != 0) {
840                 DEBUG(0,("Unable to add record %s\n", key2.dptr ));
841                 *failed = True;
842                 return -1;
843         }
844
845         if (tdb_store(tdb, data, key2, TDB_REPLACE) != 0) {
846                 DEBUG(0,("Unable to update record %s\n", data.dptr ));
847                 *failed = True;
848                 return -1;
849         }
850
851         if (tdb_delete(tdb, key) != 0) {
852                 DEBUG(0,("Unable to delete record %s\n", key.dptr ));
853                 *failed = True;
854                 return -1;
855         }
856
857         return 0;
858 }
859
860 /* These definitions are from sam/idmap_tdb.c. Replicated here just
861    out of laziness.... :-( */
862
863 /* High water mark keys */
864 #define HWM_GROUP  "GROUP HWM"
865 #define HWM_USER   "USER HWM"
866
867 /* idmap version determines auto-conversion */
868 #define IDMAP_VERSION 2
869
870
871 /*****************************************************************************
872  Convert the idmap database from an older version.
873 *****************************************************************************/
874
875 static BOOL idmap_convert(const char *idmap_name)
876 {
877         int32 vers;
878         BOOL bigendianheader;
879         BOOL failed = False;
880         TDB_CONTEXT *idmap_tdb;
881
882         if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
883                                         TDB_DEFAULT, O_RDWR,
884                                         0600))) {
885                 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
886                 return False;
887         }
888
889         bigendianheader = (idmap_tdb->flags & TDB_BIGENDIAN) ? True : False;
890
891         vers = tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION");
892
893         if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
894                 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
895                 /*
896                  * high and low records were created on a
897                  * big endian machine and will need byte-reversing.
898                  */
899
900                 int32 wm;
901
902                 wm = tdb_fetch_int32(idmap_tdb, HWM_USER);
903
904                 if (wm != -1) {
905                         wm = IREV(wm);
906                 }  else {
907                         wm = server_state.uid_low;
908                 }
909
910                 if (tdb_store_int32(idmap_tdb, HWM_USER, wm) == -1) {
911                         DEBUG(0, ("idmap_convert: Unable to byteswap user hwm in idmap database\n"));
912                         tdb_close(idmap_tdb);
913                         return False;
914                 }
915
916                 wm = tdb_fetch_int32(idmap_tdb, HWM_GROUP);
917                 if (wm != -1) {
918                         wm = IREV(wm);
919                 } else {
920                         wm = server_state.gid_low;
921                 }
922
923                 if (tdb_store_int32(idmap_tdb, HWM_GROUP, wm) == -1) {
924                         DEBUG(0, ("idmap_convert: Unable to byteswap group hwm in idmap database\n"));
925                         tdb_close(idmap_tdb);
926                         return False;
927                 }
928         }
929
930         /* the old format stored as DOMAIN/rid - now we store the SID direct */
931         tdb_traverse(idmap_tdb, convert_fn, &failed);
932
933         if (failed) {
934                 DEBUG(0, ("Problem during conversion\n"));
935                 tdb_close(idmap_tdb);
936                 return False;
937         }
938
939         if (tdb_store_int32(idmap_tdb, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
940                 DEBUG(0, ("idmap_convert: Unable to dtore idmap version in databse\n"));
941                 tdb_close(idmap_tdb);
942                 return False;
943         }
944
945         tdb_close(idmap_tdb);
946         return True;
947 }
948
949 /*****************************************************************************
950  Convert the idmap database from an older version if necessary
951 *****************************************************************************/
952
953 BOOL winbindd_upgrade_idmap(void)
954 {
955         pstring idmap_name;
956         pstring backup_name;
957         SMB_STRUCT_STAT stbuf;
958         TDB_CONTEXT *idmap_tdb;
959
960         pstrcpy(idmap_name, lock_path("winbindd_idmap.tdb"));
961
962         if (!file_exist(idmap_name, &stbuf)) {
963                 /* nothing to convert return */
964                 return True;
965         }
966
967         if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
968                                         TDB_DEFAULT, O_RDWR,
969                                         0600))) {
970                 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
971                 return False;
972         }
973
974         if (tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION") == IDMAP_VERSION) {
975                 /* nothing to convert return */
976                 tdb_close(idmap_tdb);
977                 return True;
978         }
979
980         /* backup_tdb expects the tdb not to be open */
981         tdb_close(idmap_tdb);
982
983         DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
984
985         pstrcpy(backup_name, idmap_name);
986         pstrcat(backup_name, ".bak");
987
988         if (backup_tdb(idmap_name, backup_name) != 0) {
989                 DEBUG(0, ("Could not backup idmap database\n"));
990                 return False;
991         }
992
993         return idmap_convert(idmap_name);
994 }
995
996 /*******************************************************************
997  wrapper around retrieving the trust account password
998 *******************************************************************/
999
1000 BOOL get_trust_pw(const char *domain, uint8 ret_pwd[16],
1001                           time_t *pass_last_set_time, uint32 *channel)
1002 {
1003         DOM_SID sid;
1004         char *pwd;
1005
1006         /* if we are a DC and this is not our domain, then lookup an account
1007            for the domain trust */
1008            
1009         if ( IS_DC && !strequal(domain, lp_workgroup()) && lp_allow_trusted_domains() ) 
1010         {
1011                 if ( !secrets_fetch_trusted_domain_password(domain, &pwd, &sid, 
1012                         pass_last_set_time) ) 
1013                 {
1014                         DEBUG(0, ("get_trust_pw: could not fetch trust account "
1015                                   "password for trusted domain %s\n", domain));
1016                         return False;
1017                 }
1018                 
1019                 *channel = SEC_CHAN_DOMAIN;
1020                 E_md4hash(pwd, ret_pwd);
1021                 SAFE_FREE(pwd);
1022
1023                 return True;
1024         }
1025         else    /* just get the account for our domain (covers 
1026                    ROLE_DOMAIN_MEMBER as well */
1027         {
1028                 /* get the machine trust account for our domain */
1029
1030                 if ( !secrets_fetch_trust_account_password (lp_workgroup(), ret_pwd,
1031                         pass_last_set_time, channel) ) 
1032                 {
1033                         DEBUG(0, ("get_trust_pw: could not fetch trust account "
1034                                   "password for my domain %s\n", domain));
1035                         return False;
1036                 }
1037                 
1038                 return True;
1039         }
1040         
1041         /* Failure */
1042 }
1043