r2565: syncing up for 3.0.8pre1
[tprouty/samba.git] / source / 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 = (struct winbindd_domain *)malloc(sizeof(*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         if (assume_domain(domain)) {
645                 strlcpy(name, user, sizeof(fstring));
646         } else {
647                 slprintf(name, sizeof(fstring) - 1, "%s%s%s",
648                          domain, lp_winbind_separator(),
649                          user);
650         }
651 }
652
653 /*
654  * Winbindd socket accessor functions
655  */
656
657 char *get_winbind_priv_pipe_dir(void) 
658 {
659         return lock_path(WINBINDD_PRIV_SOCKET_SUBDIR);
660 }
661
662 /* Open the winbindd socket */
663
664 static int _winbindd_socket = -1;
665 static int _winbindd_priv_socket = -1;
666
667 int open_winbindd_socket(void)
668 {
669         if (_winbindd_socket == -1) {
670                 _winbindd_socket = create_pipe_sock(
671                         WINBINDD_SOCKET_DIR, WINBINDD_SOCKET_NAME, 0755);
672                 DEBUG(10, ("open_winbindd_socket: opened socket fd %d\n",
673                            _winbindd_socket));
674         }
675
676         return _winbindd_socket;
677 }
678
679 int open_winbindd_priv_socket(void)
680 {
681         if (_winbindd_priv_socket == -1) {
682                 _winbindd_priv_socket = create_pipe_sock(
683                         get_winbind_priv_pipe_dir(), WINBINDD_SOCKET_NAME, 0750);
684                 DEBUG(10, ("open_winbindd_priv_socket: opened socket fd %d\n",
685                            _winbindd_priv_socket));
686         }
687
688         return _winbindd_priv_socket;
689 }
690
691 /* Close the winbindd socket */
692
693 void close_winbindd_socket(void)
694 {
695         if (_winbindd_socket != -1) {
696                 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
697                            _winbindd_socket));
698                 close(_winbindd_socket);
699                 _winbindd_socket = -1;
700         }
701         if (_winbindd_priv_socket != -1) {
702                 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
703                            _winbindd_priv_socket));
704                 close(_winbindd_priv_socket);
705                 _winbindd_priv_socket = -1;
706         }
707 }
708
709 /*
710  * Client list accessor functions
711  */
712
713 static struct winbindd_cli_state *_client_list;
714 static int _num_clients;
715
716 /* Return list of all connected clients */
717
718 struct winbindd_cli_state *winbindd_client_list(void)
719 {
720         return _client_list;
721 }
722
723 /* Add a connection to the list */
724
725 void winbindd_add_client(struct winbindd_cli_state *cli)
726 {
727         DLIST_ADD(_client_list, cli);
728         _num_clients++;
729 }
730
731 /* Remove a client from the list */
732
733 void winbindd_remove_client(struct winbindd_cli_state *cli)
734 {
735         DLIST_REMOVE(_client_list, cli);
736         _num_clients--;
737 }
738
739 /* Demote a client to be the last in the list */
740
741 void winbindd_demote_client(struct winbindd_cli_state *cli)
742 {
743         struct winbindd_cli_state *tmp;
744         DLIST_DEMOTE(_client_list, cli, tmp);
745 }
746
747 /* Close all open clients */
748
749 void winbindd_kill_all_clients(void)
750 {
751         struct winbindd_cli_state *cl = winbindd_client_list();
752
753         DEBUG(10, ("winbindd_kill_all_clients: going postal\n"));
754
755         while (cl) {
756                 struct winbindd_cli_state *next;
757                 
758                 next = cl->next;
759                 winbindd_remove_client(cl);
760                 cl = next;
761         }
762 }
763
764 /* Return number of open clients */
765
766 int winbindd_num_clients(void)
767 {
768         return _num_clients;
769 }
770
771 /* Help with RID -> SID conversion */
772
773 DOM_SID *rid_to_talloced_sid(struct winbindd_domain *domain,
774                                     TALLOC_CTX *mem_ctx,
775                                     uint32 rid) 
776 {
777         DOM_SID *sid;
778         sid = talloc(mem_ctx, sizeof(*sid));
779         if (!sid) {
780                 smb_panic("rid_to_to_talloced_sid: talloc for DOM_SID failed!\n");
781         }
782         sid_copy(sid, &domain->sid);
783         sid_append_rid(sid, rid);
784         return sid;
785 }
786         
787 /*****************************************************************************
788  For idmap conversion: convert one record to new format
789  Ancient versions (eg 2.2.3a) of winbindd_idmap.tdb mapped DOMAINNAME/rid
790  instead of the SID.
791 *****************************************************************************/
792 static int convert_fn(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA data, void *state)
793 {
794         struct winbindd_domain *domain;
795         char *p;
796         DOM_SID sid;
797         uint32 rid;
798         fstring keystr;
799         fstring dom_name;
800         TDB_DATA key2;
801         BOOL *failed = (BOOL *)state;
802
803         DEBUG(10,("Converting %s\n", key.dptr));
804
805         p = strchr(key.dptr, '/');
806         if (!p)
807                 return 0;
808
809         *p = 0;
810         fstrcpy(dom_name, key.dptr);
811         *p++ = '/';
812
813         domain = find_domain_from_name(dom_name);
814         if (domain == NULL) {
815                 /* We must delete the old record. */
816                 DEBUG(0,("Unable to find domain %s\n", dom_name ));
817                 DEBUG(0,("deleting record %s\n", key.dptr ));
818
819                 if (tdb_delete(tdb, key) != 0) {
820                         DEBUG(0, ("Unable to delete record %s\n", key.dptr));
821                         *failed = True;
822                         return -1;
823                 }
824
825                 return 0;
826         }
827
828         rid = atoi(p);
829
830         sid_copy(&sid, &domain->sid);
831         sid_append_rid(&sid, rid);
832
833         sid_to_string(keystr, &sid);
834         key2.dptr = keystr;
835         key2.dsize = strlen(keystr) + 1;
836
837         if (tdb_store(tdb, key2, data, TDB_INSERT) != 0) {
838                 DEBUG(0,("Unable to add record %s\n", key2.dptr ));
839                 *failed = True;
840                 return -1;
841         }
842
843         if (tdb_store(tdb, data, key2, TDB_REPLACE) != 0) {
844                 DEBUG(0,("Unable to update record %s\n", data.dptr ));
845                 *failed = True;
846                 return -1;
847         }
848
849         if (tdb_delete(tdb, key) != 0) {
850                 DEBUG(0,("Unable to delete record %s\n", key.dptr ));
851                 *failed = True;
852                 return -1;
853         }
854
855         return 0;
856 }
857
858 /* These definitions are from sam/idmap_tdb.c. Replicated here just
859    out of laziness.... :-( */
860
861 /* High water mark keys */
862 #define HWM_GROUP  "GROUP HWM"
863 #define HWM_USER   "USER HWM"
864
865 /* idmap version determines auto-conversion */
866 #define IDMAP_VERSION 2
867
868
869 /*****************************************************************************
870  Convert the idmap database from an older version.
871 *****************************************************************************/
872
873 static BOOL idmap_convert(const char *idmap_name)
874 {
875         int32 vers;
876         BOOL bigendianheader;
877         BOOL failed = False;
878         TDB_CONTEXT *idmap_tdb;
879
880         if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
881                                         TDB_DEFAULT, O_RDWR,
882                                         0600))) {
883                 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
884                 return False;
885         }
886
887         bigendianheader = (idmap_tdb->flags & TDB_BIGENDIAN) ? True : False;
888
889         vers = tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION");
890
891         if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
892                 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
893                 /*
894                  * high and low records were created on a
895                  * big endian machine and will need byte-reversing.
896                  */
897
898                 int32 wm;
899
900                 wm = tdb_fetch_int32(idmap_tdb, HWM_USER);
901
902                 if (wm != -1) {
903                         wm = IREV(wm);
904                 }  else {
905                         wm = server_state.uid_low;
906                 }
907
908                 if (tdb_store_int32(idmap_tdb, HWM_USER, wm) == -1) {
909                         DEBUG(0, ("idmap_convert: Unable to byteswap user hwm in idmap database\n"));
910                         tdb_close(idmap_tdb);
911                         return False;
912                 }
913
914                 wm = tdb_fetch_int32(idmap_tdb, HWM_GROUP);
915                 if (wm != -1) {
916                         wm = IREV(wm);
917                 } else {
918                         wm = server_state.gid_low;
919                 }
920
921                 if (tdb_store_int32(idmap_tdb, HWM_GROUP, wm) == -1) {
922                         DEBUG(0, ("idmap_convert: Unable to byteswap group hwm in idmap database\n"));
923                         tdb_close(idmap_tdb);
924                         return False;
925                 }
926         }
927
928         /* the old format stored as DOMAIN/rid - now we store the SID direct */
929         tdb_traverse(idmap_tdb, convert_fn, &failed);
930
931         if (failed) {
932                 DEBUG(0, ("Problem during conversion\n"));
933                 tdb_close(idmap_tdb);
934                 return False;
935         }
936
937         if (tdb_store_int32(idmap_tdb, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
938                 DEBUG(0, ("idmap_convert: Unable to dtore idmap version in databse\n"));
939                 tdb_close(idmap_tdb);
940                 return False;
941         }
942
943         tdb_close(idmap_tdb);
944         return True;
945 }
946
947 /*****************************************************************************
948  Convert the idmap database from an older version if necessary
949 *****************************************************************************/
950
951 BOOL winbindd_upgrade_idmap(void)
952 {
953         pstring idmap_name;
954         pstring backup_name;
955         SMB_STRUCT_STAT stbuf;
956         TDB_CONTEXT *idmap_tdb;
957
958         pstrcpy(idmap_name, lock_path("winbindd_idmap.tdb"));
959
960         if (!file_exist(idmap_name, &stbuf)) {
961                 /* nothing to convert return */
962                 return True;
963         }
964
965         if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
966                                         TDB_DEFAULT, O_RDWR,
967                                         0600))) {
968                 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
969                 return False;
970         }
971
972         if (tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION") == IDMAP_VERSION) {
973                 /* nothing to convert return */
974                 tdb_close(idmap_tdb);
975                 return True;
976         }
977
978         /* backup_tdb expects the tdb not to be open */
979         tdb_close(idmap_tdb);
980
981         DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
982
983         pstrcpy(backup_name, idmap_name);
984         pstrcat(backup_name, ".bak");
985
986         if (backup_tdb(idmap_name, backup_name) != 0) {
987                 DEBUG(0, ("Could not backup idmap database\n"));
988                 return False;
989         }
990
991         return idmap_convert(idmap_name);
992 }
993
994 /*******************************************************************
995  wrapper around retrieving the trust account password
996 *******************************************************************/
997
998 BOOL get_trust_pw(const char *domain, uint8 ret_pwd[16],
999                           time_t *pass_last_set_time, uint32 *channel)
1000 {
1001         DOM_SID sid;
1002         char *pwd;
1003
1004         /* if we are a DC and this is not our domain, then lookup an account
1005            for the domain trust */
1006            
1007         if ( IS_DC && !strequal(domain, lp_workgroup()) && lp_allow_trusted_domains() ) 
1008         {
1009                 if ( !secrets_fetch_trusted_domain_password(domain, &pwd, &sid, 
1010                         pass_last_set_time) ) 
1011                 {
1012                         DEBUG(0, ("get_trust_pw: could not fetch trust account "
1013                                   "password for trusted domain %s\n", domain));
1014                         return False;
1015                 }
1016                 
1017                 *channel = SEC_CHAN_DOMAIN;
1018                 E_md4hash(pwd, ret_pwd);
1019                 SAFE_FREE(pwd);
1020
1021                 return True;
1022         }
1023         else    /* just get the account for our domain (covers 
1024                    ROLE_DOMAIN_MEMBER as well */
1025         {
1026                 /* get the machine trust account for our domain */
1027
1028                 if ( !secrets_fetch_trust_account_password (lp_workgroup(), ret_pwd,
1029                         pass_last_set_time, channel) ) 
1030                 {
1031                         DEBUG(0, ("get_trust_pw: could not fetch trust account "
1032                                   "password for my domain %s\n", domain));
1033                         return False;
1034                 }
1035                 
1036                 return True;
1037         }
1038         
1039         /* Failure */
1040 }
1041