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