r38: Fix caching of name->sid lookups
[vlendec/samba-autobuild/.git] / source3 / nsswitch / winbindd_cache.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind cache backend functions
5
6    Copyright (C) Andrew Tridgell 2001
7    Copyright (C) Gerald Carter   2003
8    
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_WINBIND
30
31 struct winbind_cache {
32         TDB_CONTEXT *tdb;
33 };
34
35 struct cache_entry {
36         NTSTATUS status;
37         uint32 sequence_number;
38         uint8 *data;
39         uint32 len, ofs;
40 };
41
42 #define WINBINDD_MAX_CACHE_SIZE (50*1024*1024)
43
44 static struct winbind_cache *wcache;
45
46 /* flush the cache */
47 void wcache_flush_cache(void)
48 {
49         extern BOOL opt_nocache;
50
51         if (!wcache)
52                 return;
53         if (wcache->tdb) {
54                 tdb_close(wcache->tdb);
55                 wcache->tdb = NULL;
56         }
57         if (opt_nocache)
58                 return;
59
60         wcache->tdb = tdb_open_log(lock_path("winbindd_cache.tdb"), 5000, 
61                                    TDB_CLEAR_IF_FIRST, O_RDWR|O_CREAT, 0600);
62
63         if (!wcache->tdb) {
64                 DEBUG(0,("Failed to open winbindd_cache.tdb!\n"));
65         }
66         DEBUG(10,("wcache_flush_cache success\n"));
67 }
68
69 void winbindd_check_cache_size(time_t t)
70 {
71         static time_t last_check_time;
72         struct stat st;
73
74         if (last_check_time == (time_t)0)
75                 last_check_time = t;
76
77         if (t - last_check_time < 60 && t - last_check_time > 0)
78                 return;
79
80         if (wcache == NULL || wcache->tdb == NULL) {
81                 DEBUG(0, ("Unable to check size of tdb cache - cache not open !\n"));
82                 return;
83         }
84
85         if (fstat(wcache->tdb->fd, &st) == -1) {
86                 DEBUG(0, ("Unable to check size of tdb cache %s!\n", strerror(errno) ));
87                 return;
88         }
89
90         if (st.st_size > WINBINDD_MAX_CACHE_SIZE) {
91                 DEBUG(10,("flushing cache due to size (%lu) > (%lu)\n",
92                         (unsigned long)st.st_size,
93                         (unsigned long)WINBINDD_MAX_CACHE_SIZE));
94                 wcache_flush_cache();
95         }
96 }
97
98 /* get the winbind_cache structure */
99 static struct winbind_cache *get_cache(struct winbindd_domain *domain)
100 {
101         struct winbind_cache *ret = wcache;
102
103         if (!domain->backend) {
104                 extern struct winbindd_methods msrpc_methods;
105                 switch (lp_security()) {
106 #ifdef HAVE_ADS
107                 case SEC_ADS: {
108                         extern struct winbindd_methods ads_methods;
109                         /* always obey the lp_security parameter for our domain */
110                         if (domain->primary) {
111                                 domain->backend = &ads_methods;
112                                 break;
113                         }
114
115                         /* only use ADS for native modes at the momment.
116                            The problem is the correct detection of mixed 
117                            mode domains from NT4 BDC's    --jerry */
118                         
119                         if ( domain->native_mode ) {
120                                 DEBUG(5,("get_cache: Setting ADS methods for domain %s\n",
121                                         domain->name));
122                                 domain->backend = &ads_methods;
123                                 break;
124                         }
125
126                         /* fall through */
127                 }       
128 #endif
129                 default:
130                         DEBUG(5,("get_cache: Setting MS-RPC methods for domain %s\n",
131                                 domain->name));
132                         domain->backend = &msrpc_methods;
133                 }
134         }
135
136         if (ret)
137                 return ret;
138         
139         ret = smb_xmalloc(sizeof(*ret));
140         ZERO_STRUCTP(ret);
141
142         wcache = ret;
143         wcache_flush_cache();
144
145         return ret;
146 }
147
148 /*
149   free a centry structure
150 */
151 static void centry_free(struct cache_entry *centry)
152 {
153         if (!centry)
154                 return;
155         SAFE_FREE(centry->data);
156         free(centry);
157 }
158
159 /*
160   pull a uint32 from a cache entry 
161 */
162 static uint32 centry_uint32(struct cache_entry *centry)
163 {
164         uint32 ret;
165         if (centry->len - centry->ofs < 4) {
166                 DEBUG(0,("centry corruption? needed 4 bytes, have %d\n", 
167                          centry->len - centry->ofs));
168                 smb_panic("centry_uint32");
169         }
170         ret = IVAL(centry->data, centry->ofs);
171         centry->ofs += 4;
172         return ret;
173 }
174
175 /*
176   pull a uint8 from a cache entry 
177 */
178 static uint8 centry_uint8(struct cache_entry *centry)
179 {
180         uint8 ret;
181         if (centry->len - centry->ofs < 1) {
182                 DEBUG(0,("centry corruption? needed 1 bytes, have %d\n", 
183                          centry->len - centry->ofs));
184                 smb_panic("centry_uint32");
185         }
186         ret = CVAL(centry->data, centry->ofs);
187         centry->ofs += 1;
188         return ret;
189 }
190
191 /* pull a string from a cache entry, using the supplied
192    talloc context 
193 */
194 static char *centry_string(struct cache_entry *centry, TALLOC_CTX *mem_ctx)
195 {
196         uint32 len;
197         char *ret;
198
199         len = centry_uint8(centry);
200
201         if (len == 0xFF) {
202                 /* a deliberate NULL string */
203                 return NULL;
204         }
205
206         if (centry->len - centry->ofs < len) {
207                 DEBUG(0,("centry corruption? needed %d bytes, have %d\n", 
208                          len, centry->len - centry->ofs));
209                 smb_panic("centry_string");
210         }
211
212         ret = talloc(mem_ctx, len+1);
213         if (!ret) {
214                 smb_panic("centry_string out of memory\n");
215         }
216         memcpy(ret,centry->data + centry->ofs, len);
217         ret[len] = 0;
218         centry->ofs += len;
219         return ret;
220 }
221
222 /* pull a string from a cache entry, using the supplied
223    talloc context 
224 */
225 static DOM_SID *centry_sid(struct cache_entry *centry, TALLOC_CTX *mem_ctx)
226 {
227         DOM_SID *sid;
228         char *sid_string;
229
230         sid = talloc(mem_ctx, sizeof(*sid));
231         if (!sid)
232                 return NULL;
233         
234         sid_string = centry_string(centry, mem_ctx);
235         if (!string_to_sid(sid, sid_string)) {
236                 return NULL;
237         }
238         return sid;
239 }
240
241 /* the server is considered down if it can't give us a sequence number */
242 static BOOL wcache_server_down(struct winbindd_domain *domain)
243 {
244         BOOL ret;
245
246         if (!wcache->tdb)
247                 return False;
248
249         ret = (domain->sequence_number == DOM_SEQUENCE_NONE);
250
251         if (ret)
252                 DEBUG(10,("wcache_server_down: server for Domain %s down\n", 
253                         domain->name ));
254         return ret;
255 }
256
257 static NTSTATUS fetch_cache_seqnum( struct winbindd_domain *domain, time_t now )
258 {
259         TDB_DATA data;
260         fstring key;
261         uint32 time_diff;
262         
263         if (!wcache->tdb) {
264                 DEBUG(10,("fetch_cache_seqnum: tdb == NULL\n"));
265                 return NT_STATUS_UNSUCCESSFUL;
266         }
267                 
268         fstr_sprintf( key, "SEQNUM/%s", domain->name );
269         
270         data = tdb_fetch_bystring( wcache->tdb, key );
271         if ( !data.dptr || data.dsize!=8 ) {
272                 DEBUG(10,("fetch_cache_seqnum: invalid data size key [%s]\n", key ));
273                 return NT_STATUS_UNSUCCESSFUL;
274         }
275         
276         domain->sequence_number = IVAL(data.dptr, 0);
277         domain->last_seq_check  = IVAL(data.dptr, 4);
278         
279         /* have we expired? */
280         
281         time_diff = now - domain->last_seq_check;
282         if ( time_diff > lp_winbind_cache_time() ) {
283                 DEBUG(10,("fetch_cache_seqnum: timeout [%s][%u @ %u]\n",
284                         domain->name, domain->sequence_number,
285                         (uint32)domain->last_seq_check));
286                 return NT_STATUS_UNSUCCESSFUL;
287         }
288
289         DEBUG(10,("fetch_cache_seqnum: success [%s][%u @ %u]\n", 
290                 domain->name, domain->sequence_number, 
291                 (uint32)domain->last_seq_check));
292
293         return NT_STATUS_OK;
294 }
295
296 static NTSTATUS store_cache_seqnum( struct winbindd_domain *domain )
297 {
298         TDB_DATA data, key;
299         fstring key_str;
300         char buf[8];
301         
302         if (!wcache->tdb) {
303                 DEBUG(10,("store_cache_seqnum: tdb == NULL\n"));
304                 return NT_STATUS_UNSUCCESSFUL;
305         }
306                 
307         fstr_sprintf( key_str, "SEQNUM/%s", domain->name );
308         key.dptr = key_str;
309         key.dsize = strlen(key_str)+1;
310         
311         SIVAL(buf, 0, domain->sequence_number);
312         SIVAL(buf, 4, domain->last_seq_check);
313         data.dptr = buf;
314         data.dsize = 8;
315         
316         if ( tdb_store( wcache->tdb, key, data, TDB_REPLACE) == -1 ) {
317                 DEBUG(10,("store_cache_seqnum: tdb_store fail key [%s]\n", key_str ));
318                 return NT_STATUS_UNSUCCESSFUL;
319         }
320
321         DEBUG(10,("store_cache_seqnum: success [%s][%u @ %u]\n", 
322                 domain->name, domain->sequence_number, 
323                 (uint32)domain->last_seq_check));
324         
325         return NT_STATUS_OK;
326 }
327
328 /*
329   refresh the domain sequence number. If force is True
330   then always refresh it, no matter how recently we fetched it
331 */
332
333 static void refresh_sequence_number(struct winbindd_domain *domain, BOOL force)
334 {
335         NTSTATUS status;
336         unsigned time_diff;
337         time_t t = time(NULL);
338         unsigned cache_time = lp_winbind_cache_time();
339
340         get_cache( domain );
341
342 #if 0   /* JERRY -- disable as the default cache time is now 5 minutes */
343         /* trying to reconnect is expensive, don't do it too often */
344         if (domain->sequence_number == DOM_SEQUENCE_NONE) {
345                 cache_time *= 8;
346         }
347 #endif
348
349         time_diff = t - domain->last_seq_check;
350
351         /* see if we have to refetch the domain sequence number */
352         if (!force && (time_diff < cache_time)) {
353                 DEBUG(10, ("refresh_sequence_number: %s time ok\n", domain->name));
354                 goto done;
355         }
356         
357         /* try to get the sequence number from the tdb cache first */
358         /* this will update the timestamp as well */
359         
360         status = fetch_cache_seqnum( domain, t );
361         if ( NT_STATUS_IS_OK(status) )
362                 goto done;      
363
364         status = domain->backend->sequence_number(domain, &domain->sequence_number);
365
366         if (!NT_STATUS_IS_OK(status)) {
367                 domain->sequence_number = DOM_SEQUENCE_NONE;
368         }
369         
370         domain->last_status = status;
371         domain->last_seq_check = time(NULL);
372         
373         /* save the new sequence number ni the cache */
374         store_cache_seqnum( domain );
375
376 done:
377         DEBUG(10, ("refresh_sequence_number: %s seq number is now %d\n", 
378                    domain->name, domain->sequence_number));
379
380         return;
381 }
382
383 /*
384   decide if a cache entry has expired
385 */
386 static BOOL centry_expired(struct winbindd_domain *domain, const char *keystr, struct cache_entry *centry)
387 {
388         /* if the server is OK and our cache entry came from when it was down then
389            the entry is invalid */
390         if (domain->sequence_number != DOM_SEQUENCE_NONE && 
391             centry->sequence_number == DOM_SEQUENCE_NONE) {
392                 DEBUG(10,("centry_expired: Key %s for domain %s invalid sequence.\n",
393                         keystr, domain->name ));
394                 return True;
395         }
396
397         /* if the server is down or the cache entry is not older than the
398            current sequence number then it is OK */
399         if (wcache_server_down(domain) || 
400             centry->sequence_number == domain->sequence_number) {
401                 DEBUG(10,("centry_expired: Key %s for domain %s is good.\n",
402                         keystr, domain->name ));
403                 return False;
404         }
405
406         DEBUG(10,("centry_expired: Key %s for domain %s expired\n",
407                 keystr, domain->name ));
408
409         /* it's expired */
410         return True;
411 }
412
413 /*
414   fetch an entry from the cache, with a varargs key. auto-fetch the sequence
415   number and return status
416 */
417 static struct cache_entry *wcache_fetch(struct winbind_cache *cache, 
418                                         struct winbindd_domain *domain,
419                                         const char *format, ...) PRINTF_ATTRIBUTE(3,4);
420 static struct cache_entry *wcache_fetch(struct winbind_cache *cache, 
421                                         struct winbindd_domain *domain,
422                                         const char *format, ...)
423 {
424         va_list ap;
425         char *kstr;
426         TDB_DATA data;
427         struct cache_entry *centry;
428         TDB_DATA key;
429
430         refresh_sequence_number(domain, False);
431
432         va_start(ap, format);
433         smb_xvasprintf(&kstr, format, ap);
434         va_end(ap);
435         
436         key.dptr = kstr;
437         key.dsize = strlen(kstr);
438         data = tdb_fetch(wcache->tdb, key);
439         if (!data.dptr) {
440                 /* a cache miss */
441                 free(kstr);
442                 return NULL;
443         }
444
445         centry = smb_xmalloc(sizeof(*centry));
446         centry->data = (unsigned char *)data.dptr;
447         centry->len = data.dsize;
448         centry->ofs = 0;
449
450         if (centry->len < 8) {
451                 /* huh? corrupt cache? */
452                 DEBUG(10,("wcache_fetch: Corrupt cache for key %s domain %s (len < 8) ?\n",
453                         kstr, domain->name ));
454                 centry_free(centry);
455                 free(kstr);
456                 return NULL;
457         }
458         
459         centry->status = NT_STATUS(centry_uint32(centry));
460         centry->sequence_number = centry_uint32(centry);
461
462         if (centry_expired(domain, kstr, centry)) {
463                 extern BOOL opt_dual_daemon;
464
465                 DEBUG(10,("wcache_fetch: entry %s expired for domain %s\n",
466                          kstr, domain->name ));
467
468                 if (opt_dual_daemon) {
469                         extern BOOL background_process;
470                         background_process = True;
471                         DEBUG(10,("wcache_fetch: background processing expired entry %s for domain %s\n",
472                                  kstr, domain->name ));
473                 } else {
474                         centry_free(centry);
475                         free(kstr);
476                         return NULL;
477                 }
478         }
479
480         DEBUG(10,("wcache_fetch: returning entry %s for domain %s\n",
481                  kstr, domain->name ));
482
483         free(kstr);
484         return centry;
485 }
486
487 /*
488   make sure we have at least len bytes available in a centry 
489 */
490 static void centry_expand(struct cache_entry *centry, uint32 len)
491 {
492         uint8 *p;
493         if (centry->len - centry->ofs >= len)
494                 return;
495         centry->len *= 2;
496         p = realloc(centry->data, centry->len);
497         if (!p) {
498                 DEBUG(0,("out of memory: needed %d bytes in centry_expand\n", centry->len));
499                 smb_panic("out of memory in centry_expand");
500         }
501         centry->data = p;
502 }
503
504 /*
505   push a uint32 into a centry 
506 */
507 static void centry_put_uint32(struct cache_entry *centry, uint32 v)
508 {
509         centry_expand(centry, 4);
510         SIVAL(centry->data, centry->ofs, v);
511         centry->ofs += 4;
512 }
513
514 /*
515   push a uint8 into a centry 
516 */
517 static void centry_put_uint8(struct cache_entry *centry, uint8 v)
518 {
519         centry_expand(centry, 1);
520         SCVAL(centry->data, centry->ofs, v);
521         centry->ofs += 1;
522 }
523
524 /* 
525    push a string into a centry 
526  */
527 static void centry_put_string(struct cache_entry *centry, const char *s)
528 {
529         int len;
530
531         if (!s) {
532                 /* null strings are marked as len 0xFFFF */
533                 centry_put_uint8(centry, 0xFF);
534                 return;
535         }
536
537         len = strlen(s);
538         /* can't handle more than 254 char strings. Truncating is probably best */
539         if (len > 254)
540                 len = 254;
541         centry_put_uint8(centry, len);
542         centry_expand(centry, len);
543         memcpy(centry->data + centry->ofs, s, len);
544         centry->ofs += len;
545 }
546
547 static void centry_put_sid(struct cache_entry *centry, const DOM_SID *sid) 
548 {
549         fstring sid_string;
550         centry_put_string(centry, sid_to_string(sid_string, sid));
551 }
552
553 /*
554   start a centry for output. When finished, call centry_end()
555 */
556 struct cache_entry *centry_start(struct winbindd_domain *domain, NTSTATUS status)
557 {
558         struct cache_entry *centry;
559
560         if (!wcache->tdb)
561                 return NULL;
562
563         centry = smb_xmalloc(sizeof(*centry));
564
565         centry->len = 8192; /* reasonable default */
566         centry->data = smb_xmalloc(centry->len);
567         centry->ofs = 0;
568         centry->sequence_number = domain->sequence_number;
569         centry_put_uint32(centry, NT_STATUS_V(status));
570         centry_put_uint32(centry, centry->sequence_number);
571         return centry;
572 }
573
574 /*
575   finish a centry and write it to the tdb
576 */
577 static void centry_end(struct cache_entry *centry, const char *format, ...) PRINTF_ATTRIBUTE(2,3);
578 static void centry_end(struct cache_entry *centry, const char *format, ...)
579 {
580         va_list ap;
581         char *kstr;
582         TDB_DATA key, data;
583
584         va_start(ap, format);
585         smb_xvasprintf(&kstr, format, ap);
586         va_end(ap);
587
588         key.dptr = kstr;
589         key.dsize = strlen(kstr);
590         data.dptr = (char *)centry->data;
591         data.dsize = centry->ofs;
592
593         tdb_store(wcache->tdb, key, data, TDB_REPLACE);
594         free(kstr);
595 }
596
597 static void wcache_save_name_to_sid(struct winbindd_domain *domain, 
598                                     NTSTATUS status, 
599                                     const char *name, const DOM_SID *sid, 
600                                     enum SID_NAME_USE type)
601 {
602         struct cache_entry *centry;
603         fstring uname;
604         fstring sid_string;
605
606         centry = centry_start(domain, status);
607         if (!centry)
608                 return;
609         centry_put_uint32(centry, type);
610         centry_put_sid(centry, sid);
611         fstrcpy(uname, name);
612         strupper_m(uname);
613         centry_end(centry, "NS/%s/%s", domain->name, uname);
614         DEBUG(10,("wcache_save_name_to_sid: %s -> %s\n", uname, sid_string));
615         centry_free(centry);
616 }
617
618 static void wcache_save_sid_to_name(struct winbindd_domain *domain, NTSTATUS status, 
619                                     const DOM_SID *sid, const char *name, enum SID_NAME_USE type)
620 {
621         struct cache_entry *centry;
622         fstring sid_string;
623
624         centry = centry_start(domain, status);
625         if (!centry)
626                 return;
627         if (NT_STATUS_IS_OK(status)) {
628                 centry_put_uint32(centry, type);
629                 centry_put_string(centry, name);
630         }
631         centry_end(centry, "SN/%s", sid_to_string(sid_string, sid));
632         DEBUG(10,("wcache_save_sid_to_name: %s -> %s\n", sid_string, name));
633         centry_free(centry);
634 }
635
636
637 static void wcache_save_user(struct winbindd_domain *domain, NTSTATUS status, WINBIND_USERINFO *info)
638 {
639         struct cache_entry *centry;
640         fstring sid_string;
641
642         centry = centry_start(domain, status);
643         if (!centry)
644                 return;
645         centry_put_string(centry, info->acct_name);
646         centry_put_string(centry, info->full_name);
647         centry_put_sid(centry, info->user_sid);
648         centry_put_sid(centry, info->group_sid);
649         centry_end(centry, "U/%s", sid_to_string(sid_string, info->user_sid));
650         DEBUG(10,("wcache_save_user: %s (acct_name %s)\n", sid_string, info->acct_name));
651         centry_free(centry);
652 }
653
654
655 /* Query display info. This is the basic user list fn */
656 static NTSTATUS query_user_list(struct winbindd_domain *domain,
657                                 TALLOC_CTX *mem_ctx,
658                                 uint32 *num_entries, 
659                                 WINBIND_USERINFO **info)
660 {
661         struct winbind_cache *cache = get_cache(domain);
662         struct cache_entry *centry = NULL;
663         NTSTATUS status;
664         unsigned int i, retry;
665
666         if (!cache->tdb)
667                 goto do_query;
668
669         centry = wcache_fetch(cache, domain, "UL/%s", domain->name);
670         if (!centry)
671                 goto do_query;
672
673         *num_entries = centry_uint32(centry);
674         
675         if (*num_entries == 0)
676                 goto do_cached;
677
678         (*info) = talloc(mem_ctx, sizeof(**info) * (*num_entries));
679         if (! (*info))
680                 smb_panic("query_user_list out of memory");
681         for (i=0; i<(*num_entries); i++) {
682                 (*info)[i].acct_name = centry_string(centry, mem_ctx);
683                 (*info)[i].full_name = centry_string(centry, mem_ctx);
684                 (*info)[i].user_sid = centry_sid(centry, mem_ctx);
685                 (*info)[i].group_sid = centry_sid(centry, mem_ctx);
686         }
687
688 do_cached:      
689         status = centry->status;
690
691         DEBUG(10,("query_user_list: [Cached] - cached list for domain %s status %s\n",
692                 domain->name, get_friendly_nt_error_msg(status) ));
693
694         centry_free(centry);
695         return status;
696
697 do_query:
698         *num_entries = 0;
699         *info = NULL;
700
701         /* Return status value returned by seq number check */
702
703         if (!NT_STATUS_IS_OK(domain->last_status))
704                 return domain->last_status;
705
706         /* Put the query_user_list() in a retry loop.  There appears to be
707          * some bug either with Windows 2000 or Samba's handling of large
708          * rpc replies.  This manifests itself as sudden disconnection
709          * at a random point in the enumeration of a large (60k) user list.
710          * The retry loop simply tries the operation again. )-:  It's not
711          * pretty but an acceptable workaround until we work out what the
712          * real problem is. */
713
714         retry = 0;
715         do {
716
717                 DEBUG(10,("query_user_list: [Cached] - doing backend query for list for domain %s\n",
718                         domain->name ));
719
720                 status = domain->backend->query_user_list(domain, mem_ctx, num_entries, info);
721                 if (!NT_STATUS_IS_OK(status))
722                         DEBUG(3, ("query_user_list: returned 0x%08x, retrying\n", NT_STATUS_V(status)));
723                         if (NT_STATUS_V(status) == NT_STATUS_V(NT_STATUS_UNSUCCESSFUL)) {
724                                 DEBUG(3, ("query_user_list: flushing connection cache\n"));
725                                 winbindd_cm_flush();
726                         }
727
728         } while (NT_STATUS_V(status) == NT_STATUS_V(NT_STATUS_UNSUCCESSFUL) && 
729                  (retry++ < 5));
730
731         /* and save it */
732         refresh_sequence_number(domain, False);
733         centry = centry_start(domain, status);
734         if (!centry)
735                 goto skip_save;
736         centry_put_uint32(centry, *num_entries);
737         for (i=0; i<(*num_entries); i++) {
738                 centry_put_string(centry, (*info)[i].acct_name);
739                 centry_put_string(centry, (*info)[i].full_name);
740                 centry_put_sid(centry, (*info)[i].user_sid);
741                 centry_put_sid(centry, (*info)[i].group_sid);
742                 if (domain->backend->consistent) {
743                         /* when the backend is consistent we can pre-prime some mappings */
744                         wcache_save_name_to_sid(domain, NT_STATUS_OK, 
745                                                 (*info)[i].acct_name, 
746                                                 (*info)[i].user_sid,
747                                                 SID_NAME_USER);
748                         wcache_save_sid_to_name(domain, NT_STATUS_OK, 
749                                                 (*info)[i].user_sid,
750                                                 (*info)[i].acct_name, 
751                                                 SID_NAME_USER);
752                         wcache_save_user(domain, NT_STATUS_OK, &(*info)[i]);
753                 }
754         }       
755         centry_end(centry, "UL/%s", domain->name);
756         centry_free(centry);
757
758 skip_save:
759         return status;
760 }
761
762 /* list all domain groups */
763 static NTSTATUS enum_dom_groups(struct winbindd_domain *domain,
764                                 TALLOC_CTX *mem_ctx,
765                                 uint32 *num_entries, 
766                                 struct acct_info **info)
767 {
768         struct winbind_cache *cache = get_cache(domain);
769         struct cache_entry *centry = NULL;
770         NTSTATUS status;
771         unsigned int i;
772
773         if (!cache->tdb)
774                 goto do_query;
775
776         centry = wcache_fetch(cache, domain, "GL/%s/domain", domain->name);
777         if (!centry)
778                 goto do_query;
779
780         *num_entries = centry_uint32(centry);
781         
782         if (*num_entries == 0)
783                 goto do_cached;
784
785         (*info) = talloc(mem_ctx, sizeof(**info) * (*num_entries));
786         if (! (*info))
787                 smb_panic("enum_dom_groups out of memory");
788         for (i=0; i<(*num_entries); i++) {
789                 fstrcpy((*info)[i].acct_name, centry_string(centry, mem_ctx));
790                 fstrcpy((*info)[i].acct_desc, centry_string(centry, mem_ctx));
791                 (*info)[i].rid = centry_uint32(centry);
792         }
793
794 do_cached:      
795         status = centry->status;
796
797         DEBUG(10,("enum_dom_groups: [Cached] - cached list for domain %s status %s\n",
798                 domain->name, get_friendly_nt_error_msg(status) ));
799
800         centry_free(centry);
801         return status;
802
803 do_query:
804         *num_entries = 0;
805         *info = NULL;
806
807         /* Return status value returned by seq number check */
808
809         if (!NT_STATUS_IS_OK(domain->last_status))
810                 return domain->last_status;
811
812         DEBUG(10,("enum_dom_groups: [Cached] - doing backend query for list for domain %s\n",
813                 domain->name ));
814
815         status = domain->backend->enum_dom_groups(domain, mem_ctx, num_entries, info);
816
817         /* and save it */
818         refresh_sequence_number(domain, False);
819         centry = centry_start(domain, status);
820         if (!centry)
821                 goto skip_save;
822         centry_put_uint32(centry, *num_entries);
823         for (i=0; i<(*num_entries); i++) {
824                 centry_put_string(centry, (*info)[i].acct_name);
825                 centry_put_string(centry, (*info)[i].acct_desc);
826                 centry_put_uint32(centry, (*info)[i].rid);
827         }       
828         centry_end(centry, "GL/%s/domain", domain->name);
829         centry_free(centry);
830
831 skip_save:
832         return status;
833 }
834
835 /* list all domain groups */
836 static NTSTATUS enum_local_groups(struct winbindd_domain *domain,
837                                 TALLOC_CTX *mem_ctx,
838                                 uint32 *num_entries, 
839                                 struct acct_info **info)
840 {
841         struct winbind_cache *cache = get_cache(domain);
842         struct cache_entry *centry = NULL;
843         NTSTATUS status;
844         unsigned int i;
845
846         if (!cache->tdb)
847                 goto do_query;
848
849         centry = wcache_fetch(cache, domain, "GL/%s/local", domain->name);
850         if (!centry)
851                 goto do_query;
852
853         *num_entries = centry_uint32(centry);
854         
855         if (*num_entries == 0)
856                 goto do_cached;
857
858         (*info) = talloc(mem_ctx, sizeof(**info) * (*num_entries));
859         if (! (*info))
860                 smb_panic("enum_dom_groups out of memory");
861         for (i=0; i<(*num_entries); i++) {
862                 fstrcpy((*info)[i].acct_name, centry_string(centry, mem_ctx));
863                 fstrcpy((*info)[i].acct_desc, centry_string(centry, mem_ctx));
864                 (*info)[i].rid = centry_uint32(centry);
865         }
866
867 do_cached:      
868
869         /* If we are returning cached data and the domain controller
870            is down then we don't know whether the data is up to date
871            or not.  Return NT_STATUS_MORE_PROCESSING_REQUIRED to
872            indicate this. */
873
874         if (wcache_server_down(domain)) {
875                 DEBUG(10, ("enum_local_groups: returning cached user list and server was down\n"));
876                 status = NT_STATUS_MORE_PROCESSING_REQUIRED;
877         } else
878                 status = centry->status;
879
880         DEBUG(10,("enum_local_groups: [Cached] - cached list for domain %s status %s\n",
881                 domain->name, get_friendly_nt_error_msg(status) ));
882
883         centry_free(centry);
884         return status;
885
886 do_query:
887         *num_entries = 0;
888         *info = NULL;
889
890         /* Return status value returned by seq number check */
891
892         if (!NT_STATUS_IS_OK(domain->last_status))
893                 return domain->last_status;
894
895         DEBUG(10,("enum_local_groups: [Cached] - doing backend query for list for domain %s\n",
896                 domain->name ));
897
898         status = domain->backend->enum_local_groups(domain, mem_ctx, num_entries, info);
899
900         /* and save it */
901         refresh_sequence_number(domain, False);
902         centry = centry_start(domain, status);
903         if (!centry)
904                 goto skip_save;
905         centry_put_uint32(centry, *num_entries);
906         for (i=0; i<(*num_entries); i++) {
907                 centry_put_string(centry, (*info)[i].acct_name);
908                 centry_put_string(centry, (*info)[i].acct_desc);
909                 centry_put_uint32(centry, (*info)[i].rid);
910         }
911         centry_end(centry, "GL/%s/local", domain->name);
912         centry_free(centry);
913
914 skip_save:
915         return status;
916 }
917
918 /* convert a single name to a sid in a domain */
919 static NTSTATUS name_to_sid(struct winbindd_domain *domain,
920                             TALLOC_CTX *mem_ctx,
921                             const char *name,
922                             DOM_SID *sid,
923                             enum SID_NAME_USE *type)
924 {
925         struct winbind_cache *cache = get_cache(domain);
926         struct cache_entry *centry = NULL;
927         NTSTATUS status;
928         fstring uname;
929         DOM_SID *sid2;
930
931         if (!cache->tdb)
932                 goto do_query;
933
934         fstrcpy(uname, name);
935         strupper_m(uname);
936         centry = wcache_fetch(cache, domain, "NS/%s/%s", domain->name, uname);
937         if (!centry)
938                 goto do_query;
939         *type = (enum SID_NAME_USE)centry_uint32(centry);
940         sid2 = centry_sid(centry, mem_ctx);
941         if (!sid2) {
942                 ZERO_STRUCTP(sid);
943         } else {
944                 sid_copy(sid, sid2);
945         }
946
947         status = centry->status;
948
949         DEBUG(10,("name_to_sid: [Cached] - cached name for domain %s status %s\n",
950                 domain->name, get_friendly_nt_error_msg(status) ));
951
952         centry_free(centry);
953         return status;
954
955 do_query:
956         ZERO_STRUCTP(sid);
957
958         /* If the seq number check indicated that there is a problem
959          * with this DC, then return that status... except for
960          * access_denied.  This is special because the dc may be in
961          * "restrict anonymous = 1" mode, in which case it will deny
962          * most unauthenticated operations, but *will* allow the LSA
963          * name-to-sid that we try as a fallback. */
964
965         if (!(NT_STATUS_IS_OK(domain->last_status)
966               || NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED)))
967                 return domain->last_status;
968
969         DEBUG(10,("name_to_sid: [Cached] - doing backend query for name for domain %s\n",
970                 domain->name ));
971
972         status = domain->backend->name_to_sid(domain, mem_ctx, name, sid, type);
973
974         /* and save it */
975         wcache_save_name_to_sid(domain, status, name, sid, *type);
976
977         /* We can't save the sid to name mapping as we don't know the
978            correct case of the name without looking it up */
979
980         return status;
981 }
982
983 /* convert a sid to a user or group name. The sid is guaranteed to be in the domain
984    given */
985 static NTSTATUS sid_to_name(struct winbindd_domain *domain,
986                             TALLOC_CTX *mem_ctx,
987                             const DOM_SID *sid,
988                             char **name,
989                             enum SID_NAME_USE *type)
990 {
991         struct winbind_cache *cache = get_cache(domain);
992         struct cache_entry *centry = NULL;
993         NTSTATUS status;
994         fstring sid_string;
995
996         if (!cache->tdb)
997                 goto do_query;
998
999         centry = wcache_fetch(cache, domain, "SN/%s", sid_to_string(sid_string, sid));
1000         if (!centry)
1001                 goto do_query;
1002         if (NT_STATUS_IS_OK(centry->status)) {
1003                 *type = (enum SID_NAME_USE)centry_uint32(centry);
1004                 *name = centry_string(centry, mem_ctx);
1005         }
1006         status = centry->status;
1007
1008         DEBUG(10,("sid_to_name: [Cached] - cached name for domain %s status %s\n",
1009                 domain->name, get_friendly_nt_error_msg(status) ));
1010
1011         centry_free(centry);
1012         return status;
1013
1014 do_query:
1015         *name = NULL;
1016
1017         /* If the seq number check indicated that there is a problem
1018          * with this DC, then return that status... except for
1019          * access_denied.  This is special because the dc may be in
1020          * "restrict anonymous = 1" mode, in which case it will deny
1021          * most unauthenticated operations, but *will* allow the LSA
1022          * sid-to-name that we try as a fallback. */
1023
1024         if (!(NT_STATUS_IS_OK(domain->last_status)
1025               || NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED)))
1026                 return domain->last_status;
1027
1028         DEBUG(10,("sid_to_name: [Cached] - doing backend query for name for domain %s\n",
1029                 domain->name ));
1030
1031         status = domain->backend->sid_to_name(domain, mem_ctx, sid, name, type);
1032
1033         /* and save it */
1034         refresh_sequence_number(domain, False);
1035         wcache_save_sid_to_name(domain, status, sid, *name, *type);
1036         wcache_save_name_to_sid(domain, status, *name, sid, *type);
1037
1038         return status;
1039 }
1040
1041
1042 /* Lookup user information from a rid */
1043 static NTSTATUS query_user(struct winbindd_domain *domain, 
1044                            TALLOC_CTX *mem_ctx, 
1045                            const DOM_SID *user_sid, 
1046                            WINBIND_USERINFO *info)
1047 {
1048         struct winbind_cache *cache = get_cache(domain);
1049         struct cache_entry *centry = NULL;
1050         NTSTATUS status;
1051
1052         if (!cache->tdb)
1053                 goto do_query;
1054
1055         centry = wcache_fetch(cache, domain, "U/%s", sid_string_static(user_sid));
1056         
1057         /* If we have an access denied cache entry and a cached info3 in the
1058            samlogon cache then do a query.  This will force the rpc back end
1059            to return the info3 data. */
1060
1061         if (NT_STATUS_V(domain->last_status) == NT_STATUS_V(NT_STATUS_ACCESS_DENIED) &&
1062             netsamlogon_cache_have(user_sid)) {
1063                 DEBUG(10, ("query_user: cached access denied and have cached info3\n"));
1064                 domain->last_status = NT_STATUS_OK;
1065                 centry_free(centry);
1066                 goto do_query;
1067         }
1068         
1069         if (!centry)
1070                 goto do_query;
1071
1072         info->acct_name = centry_string(centry, mem_ctx);
1073         info->full_name = centry_string(centry, mem_ctx);
1074         info->user_sid = centry_sid(centry, mem_ctx);
1075         info->group_sid = centry_sid(centry, mem_ctx);
1076         status = centry->status;
1077
1078         DEBUG(10,("query_user: [Cached] - cached info for domain %s status %s\n",
1079                 domain->name, get_friendly_nt_error_msg(status) ));
1080
1081         centry_free(centry);
1082         return status;
1083
1084 do_query:
1085         ZERO_STRUCTP(info);
1086
1087         /* Return status value returned by seq number check */
1088
1089         if (!NT_STATUS_IS_OK(domain->last_status))
1090                 return domain->last_status;
1091         
1092         DEBUG(10,("sid_to_name: [Cached] - doing backend query for info for domain %s\n",
1093                 domain->name ));
1094
1095         status = domain->backend->query_user(domain, mem_ctx, user_sid, info);
1096
1097         /* and save it */
1098         refresh_sequence_number(domain, False);
1099         wcache_save_user(domain, status, info);
1100
1101         return status;
1102 }
1103
1104
1105 /* Lookup groups a user is a member of. */
1106 static NTSTATUS lookup_usergroups(struct winbindd_domain *domain,
1107                                   TALLOC_CTX *mem_ctx,
1108                                   const DOM_SID *user_sid, 
1109                                   uint32 *num_groups, DOM_SID ***user_gids)
1110 {
1111         struct winbind_cache *cache = get_cache(domain);
1112         struct cache_entry *centry = NULL;
1113         NTSTATUS status;
1114         unsigned int i;
1115         fstring sid_string;
1116
1117         if (!cache->tdb)
1118                 goto do_query;
1119
1120         centry = wcache_fetch(cache, domain, "UG/%s", sid_to_string(sid_string, user_sid));
1121         
1122         /* If we have an access denied cache entry and a cached info3 in the
1123            samlogon cache then do a query.  This will force the rpc back end
1124            to return the info3 data. */
1125
1126         if (NT_STATUS_V(domain->last_status) == NT_STATUS_V(NT_STATUS_ACCESS_DENIED) &&
1127             netsamlogon_cache_have(user_sid)) {
1128                 DEBUG(10, ("query_user: cached access denied and have cached info3\n"));
1129                 domain->last_status = NT_STATUS_OK;
1130                 centry_free(centry);
1131                 goto do_query;
1132         }
1133         
1134         if (!centry)
1135                 goto do_query;
1136
1137         *num_groups = centry_uint32(centry);
1138         
1139         if (*num_groups == 0)
1140                 goto do_cached;
1141
1142         (*user_gids) = talloc(mem_ctx, sizeof(**user_gids) * (*num_groups));
1143         if (! (*user_gids))
1144                 smb_panic("lookup_usergroups out of memory");
1145         for (i=0; i<(*num_groups); i++) {
1146                 (*user_gids)[i] = centry_sid(centry, mem_ctx);
1147         }
1148
1149 do_cached:      
1150         status = centry->status;
1151
1152         DEBUG(10,("lookup_usergroups: [Cached] - cached info for domain %s status %s\n",
1153                 domain->name, get_friendly_nt_error_msg(status) ));
1154
1155         centry_free(centry);
1156         return status;
1157
1158 do_query:
1159         (*num_groups) = 0;
1160         (*user_gids) = NULL;
1161
1162         /* Return status value returned by seq number check */
1163
1164         if (!NT_STATUS_IS_OK(domain->last_status))
1165                 return domain->last_status;
1166
1167         DEBUG(10,("lookup_usergroups: [Cached] - doing backend query for info for domain %s\n",
1168                 domain->name ));
1169
1170         status = domain->backend->lookup_usergroups(domain, mem_ctx, user_sid, num_groups, user_gids);
1171
1172         /* and save it */
1173         refresh_sequence_number(domain, False);
1174         centry = centry_start(domain, status);
1175         if (!centry)
1176                 goto skip_save;
1177         centry_put_uint32(centry, *num_groups);
1178         for (i=0; i<(*num_groups); i++) {
1179                 centry_put_sid(centry, (*user_gids)[i]);
1180         }       
1181         centry_end(centry, "UG/%s", sid_to_string(sid_string, user_sid));
1182         centry_free(centry);
1183
1184 skip_save:
1185         return status;
1186 }
1187
1188
1189 static NTSTATUS lookup_groupmem(struct winbindd_domain *domain,
1190                                 TALLOC_CTX *mem_ctx,
1191                                 const DOM_SID *group_sid, uint32 *num_names, 
1192                                 DOM_SID ***sid_mem, char ***names, 
1193                                 uint32 **name_types)
1194 {
1195         struct winbind_cache *cache = get_cache(domain);
1196         struct cache_entry *centry = NULL;
1197         NTSTATUS status;
1198         unsigned int i;
1199         fstring sid_string;
1200
1201         if (!cache->tdb)
1202                 goto do_query;
1203
1204         centry = wcache_fetch(cache, domain, "GM/%s", sid_to_string(sid_string, group_sid));
1205         if (!centry)
1206                 goto do_query;
1207
1208         *num_names = centry_uint32(centry);
1209         
1210         if (*num_names == 0)
1211                 goto do_cached;
1212
1213         (*sid_mem) = talloc(mem_ctx, sizeof(**sid_mem) * (*num_names));
1214         (*names) = talloc(mem_ctx, sizeof(**names) * (*num_names));
1215         (*name_types) = talloc(mem_ctx, sizeof(**name_types) * (*num_names));
1216
1217         if (! (*sid_mem) || ! (*names) || ! (*name_types)) {
1218                 smb_panic("lookup_groupmem out of memory");
1219         }
1220
1221         for (i=0; i<(*num_names); i++) {
1222                 (*sid_mem)[i] = centry_sid(centry, mem_ctx);
1223                 (*names)[i] = centry_string(centry, mem_ctx);
1224                 (*name_types)[i] = centry_uint32(centry);
1225         }
1226
1227 do_cached:      
1228         status = centry->status;
1229
1230         DEBUG(10,("lookup_groupmem: [Cached] - cached info for domain %s status %s\n",
1231                 domain->name, get_friendly_nt_error_msg(status) ));
1232
1233         centry_free(centry);
1234         return status;
1235
1236 do_query:
1237         (*num_names) = 0;
1238         (*sid_mem) = NULL;
1239         (*names) = NULL;
1240         (*name_types) = NULL;
1241         
1242         /* Return status value returned by seq number check */
1243
1244         if (!NT_STATUS_IS_OK(domain->last_status))
1245                 return domain->last_status;
1246
1247         DEBUG(10,("lookup_groupmem: [Cached] - doing backend query for info for domain %s\n",
1248                 domain->name ));
1249
1250         status = domain->backend->lookup_groupmem(domain, mem_ctx, group_sid, num_names, 
1251                                                   sid_mem, names, name_types);
1252
1253         /* and save it */
1254         refresh_sequence_number(domain, False);
1255         centry = centry_start(domain, status);
1256         if (!centry)
1257                 goto skip_save;
1258         centry_put_uint32(centry, *num_names);
1259         for (i=0; i<(*num_names); i++) {
1260                 centry_put_sid(centry, (*sid_mem)[i]);
1261                 centry_put_string(centry, (*names)[i]);
1262                 centry_put_uint32(centry, (*name_types)[i]);
1263         }       
1264         centry_end(centry, "GM/%s", sid_to_string(sid_string, group_sid));
1265         centry_free(centry);
1266
1267 skip_save:
1268         return status;
1269 }
1270
1271 /* find the sequence number for a domain */
1272 static NTSTATUS sequence_number(struct winbindd_domain *domain, uint32 *seq)
1273 {
1274         refresh_sequence_number(domain, False);
1275
1276         *seq = domain->sequence_number;
1277
1278         return NT_STATUS_OK;
1279 }
1280
1281 /* enumerate trusted domains */
1282 static NTSTATUS trusted_domains(struct winbindd_domain *domain,
1283                                 TALLOC_CTX *mem_ctx,
1284                                 uint32 *num_domains,
1285                                 char ***names,
1286                                 char ***alt_names,
1287                                 DOM_SID **dom_sids)
1288 {
1289         get_cache(domain);
1290
1291         DEBUG(10,("trusted_domains: [Cached] - doing backend query for info for domain %s\n",
1292                 domain->name ));
1293
1294         /* we don't cache this call */
1295         return domain->backend->trusted_domains(domain, mem_ctx, num_domains, 
1296                                                names, alt_names, dom_sids);
1297 }
1298
1299 /* find the domain sid */
1300 static NTSTATUS domain_sid(struct winbindd_domain *domain, DOM_SID *sid)
1301 {
1302         get_cache(domain);
1303
1304         DEBUG(10,("domain_sid: [Cached] - doing backend query for info for domain %s\n",
1305                 domain->name ));
1306
1307         /* we don't cache this call */
1308         return domain->backend->domain_sid(domain, sid);
1309 }
1310
1311 /* find the alternate names for the domain, if any */
1312 static NTSTATUS alternate_name(struct winbindd_domain *domain)
1313 {
1314         get_cache(domain);
1315
1316         DEBUG(10,("alternate_name: [Cached] - doing backend query for info for domain %s\n",
1317                 domain->name ));
1318
1319         /* we don't cache this call */
1320         return domain->backend->alternate_name(domain);
1321 }
1322
1323 /* Invalidate cached user and group lists coherently */
1324
1325 static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, 
1326                        void *state)
1327 {
1328         if (strncmp(kbuf.dptr, "UL/", 3) == 0 ||
1329             strncmp(kbuf.dptr, "GL/", 3) == 0)
1330                 tdb_delete(the_tdb, kbuf);
1331
1332         return 0;
1333 }
1334
1335 /* Invalidate the getpwnam and getgroups entries for a winbindd domain */
1336
1337 void wcache_invalidate_samlogon(struct winbindd_domain *domain, 
1338                                 NET_USER_INFO_3 *info3)
1339 {
1340         struct winbind_cache *cache;
1341         
1342         if (!domain)
1343                 return;
1344
1345         cache = get_cache(domain);
1346         netsamlogon_clear_cached_user(cache->tdb, info3);
1347 }
1348
1349 void wcache_invalidate_cache(void)
1350 {
1351         struct winbindd_domain *domain;
1352
1353         for (domain = domain_list(); domain; domain = domain->next) {
1354                 struct winbind_cache *cache = get_cache(domain);
1355
1356                 DEBUG(10, ("wcache_invalidate_cache: invalidating cache "
1357                            "entries for %s\n", domain->name));
1358                 if (cache)
1359                         tdb_traverse(cache->tdb, traverse_fn, NULL);
1360         }
1361 }
1362
1363 /* the ADS backend methods are exposed via this structure */
1364 struct winbindd_methods cache_methods = {
1365         True,
1366         query_user_list,
1367         enum_dom_groups,
1368         enum_local_groups,
1369         name_to_sid,
1370         sid_to_name,
1371         query_user,
1372         lookup_usergroups,
1373         lookup_groupmem,
1374         sequence_number,
1375         trusted_domains,
1376         domain_sid,
1377         alternate_name
1378 };