w3:winbind: Convert WINBINDD_ALLOCATE_GID to the new API
[Samba/aatanasov.git] / source3 / winbindd / winbindd_cache.c
blob8d44d27141467d24b9a917db7e4258ababbfc5c0
1 /*
2 Unix SMB/CIFS implementation.
4 Winbind cache backend functions
6 Copyright (C) Andrew Tridgell 2001
7 Copyright (C) Gerald Carter 2003-2007
8 Copyright (C) Volker Lendecke 2005
9 Copyright (C) Guenther Deschner 2005
10 Copyright (C) Michael Adam 2007
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 3 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #include "includes.h"
27 #include "winbindd.h"
28 #include "tdb_validate.h"
29 #include "../libcli/auth/libcli_auth.h"
30 #include "../librpc/gen_ndr/ndr_wbint.h"
32 #undef DBGC_CLASS
33 #define DBGC_CLASS DBGC_WINBIND
35 #define WINBINDD_CACHE_VERSION 1
36 #define WINBINDD_CACHE_VERSION_KEYSTR "WINBINDD_CACHE_VERSION"
38 extern struct winbindd_methods reconnect_methods;
39 #ifdef HAVE_ADS
40 extern struct winbindd_methods ads_methods;
41 #endif
42 extern struct winbindd_methods builtin_passdb_methods;
45 * JRA. KEEP THIS LIST UP TO DATE IF YOU ADD CACHE ENTRIES.
46 * Here are the list of entry types that are *not* stored
47 * as form struct cache_entry in the cache.
50 static const char *non_centry_keys[] = {
51 "SEQNUM/",
52 "DR/",
53 "DE/",
54 "WINBINDD_OFFLINE",
55 WINBINDD_CACHE_VERSION_KEYSTR,
56 NULL
59 /************************************************************************
60 Is this key a non-centry type ?
61 ************************************************************************/
63 static bool is_non_centry_key(TDB_DATA kbuf)
65 int i;
67 if (kbuf.dptr == NULL || kbuf.dsize == 0) {
68 return false;
70 for (i = 0; non_centry_keys[i] != NULL; i++) {
71 size_t namelen = strlen(non_centry_keys[i]);
72 if (kbuf.dsize < namelen) {
73 continue;
75 if (strncmp(non_centry_keys[i], (const char *)kbuf.dptr, namelen) == 0) {
76 return true;
79 return false;
82 /* Global online/offline state - False when online. winbindd starts up online
83 and sets this to true if the first query fails and there's an entry in
84 the cache tdb telling us to stay offline. */
86 static bool global_winbindd_offline_state;
88 struct winbind_cache {
89 TDB_CONTEXT *tdb;
92 struct cache_entry {
93 NTSTATUS status;
94 uint32 sequence_number;
95 uint8 *data;
96 uint32 len, ofs;
99 void (*smb_panic_fn)(const char *const why) = smb_panic;
101 #define WINBINDD_MAX_CACHE_SIZE (50*1024*1024)
103 static struct winbind_cache *wcache;
105 void winbindd_check_cache_size(time_t t)
107 static time_t last_check_time;
108 struct stat st;
110 if (last_check_time == (time_t)0)
111 last_check_time = t;
113 if (t - last_check_time < 60 && t - last_check_time > 0)
114 return;
116 if (wcache == NULL || wcache->tdb == NULL) {
117 DEBUG(0, ("Unable to check size of tdb cache - cache not open !\n"));
118 return;
121 if (fstat(tdb_fd(wcache->tdb), &st) == -1) {
122 DEBUG(0, ("Unable to check size of tdb cache %s!\n", strerror(errno) ));
123 return;
126 if (st.st_size > WINBINDD_MAX_CACHE_SIZE) {
127 DEBUG(10,("flushing cache due to size (%lu) > (%lu)\n",
128 (unsigned long)st.st_size,
129 (unsigned long)WINBINDD_MAX_CACHE_SIZE));
130 wcache_flush_cache();
134 /* get the winbind_cache structure */
135 static struct winbind_cache *get_cache(struct winbindd_domain *domain)
137 struct winbind_cache *ret = wcache;
139 /* We have to know what type of domain we are dealing with first. */
141 if (domain->internal) {
142 domain->backend = &builtin_passdb_methods;
143 domain->initialized = True;
145 if ( !domain->initialized ) {
146 init_dc_connection( domain );
150 OK. listen up becasue I'm only going to say this once.
151 We have the following scenarios to consider
152 (a) trusted AD domains on a Samba DC,
153 (b) trusted AD domains and we are joined to a non-kerberos domain
154 (c) trusted AD domains and we are joined to a kerberos (AD) domain
156 For (a) we can always contact the trusted domain using krb5
157 since we have the domain trust account password
159 For (b) we can only use RPC since we have no way of
160 getting a krb5 ticket in our own domain
162 For (c) we can always use krb5 since we have a kerberos trust
164 --jerry
167 if (!domain->backend) {
168 #ifdef HAVE_ADS
169 struct winbindd_domain *our_domain = domain;
171 /* find our domain first so we can figure out if we
172 are joined to a kerberized domain */
174 if ( !domain->primary )
175 our_domain = find_our_domain();
177 if ((our_domain->active_directory || IS_DC)
178 && domain->active_directory
179 && !lp_winbind_rpc_only()) {
180 DEBUG(5,("get_cache: Setting ADS methods for domain %s\n", domain->name));
181 domain->backend = &ads_methods;
182 } else {
183 #endif /* HAVE_ADS */
184 DEBUG(5,("get_cache: Setting MS-RPC methods for domain %s\n", domain->name));
185 domain->backend = &reconnect_methods;
186 #ifdef HAVE_ADS
188 #endif /* HAVE_ADS */
191 if (ret)
192 return ret;
194 ret = SMB_XMALLOC_P(struct winbind_cache);
195 ZERO_STRUCTP(ret);
197 wcache = ret;
198 wcache_flush_cache();
200 return ret;
204 free a centry structure
206 static void centry_free(struct cache_entry *centry)
208 if (!centry)
209 return;
210 SAFE_FREE(centry->data);
211 free(centry);
214 static bool centry_check_bytes(struct cache_entry *centry, size_t nbytes)
216 if (centry->len - centry->ofs < nbytes) {
217 DEBUG(0,("centry corruption? needed %u bytes, have %d\n",
218 (unsigned int)nbytes,
219 centry->len - centry->ofs));
220 return false;
222 return true;
226 pull a uint32 from a cache entry
228 static uint32 centry_uint32(struct cache_entry *centry)
230 uint32 ret;
232 if (!centry_check_bytes(centry, 4)) {
233 smb_panic_fn("centry_uint32");
235 ret = IVAL(centry->data, centry->ofs);
236 centry->ofs += 4;
237 return ret;
241 pull a uint16 from a cache entry
243 static uint16 centry_uint16(struct cache_entry *centry)
245 uint16 ret;
246 if (!centry_check_bytes(centry, 2)) {
247 smb_panic_fn("centry_uint16");
249 ret = CVAL(centry->data, centry->ofs);
250 centry->ofs += 2;
251 return ret;
255 pull a uint8 from a cache entry
257 static uint8 centry_uint8(struct cache_entry *centry)
259 uint8 ret;
260 if (!centry_check_bytes(centry, 1)) {
261 smb_panic_fn("centry_uint8");
263 ret = CVAL(centry->data, centry->ofs);
264 centry->ofs += 1;
265 return ret;
269 pull a NTTIME from a cache entry
271 static NTTIME centry_nttime(struct cache_entry *centry)
273 NTTIME ret;
274 if (!centry_check_bytes(centry, 8)) {
275 smb_panic_fn("centry_nttime");
277 ret = IVAL(centry->data, centry->ofs);
278 centry->ofs += 4;
279 ret += (uint64_t)IVAL(centry->data, centry->ofs) << 32;
280 centry->ofs += 4;
281 return ret;
285 pull a time_t from a cache entry. time_t stored portably as a 64-bit time.
287 static time_t centry_time(struct cache_entry *centry)
289 return (time_t)centry_nttime(centry);
292 /* pull a string from a cache entry, using the supplied
293 talloc context
295 static char *centry_string(struct cache_entry *centry, TALLOC_CTX *mem_ctx)
297 uint32 len;
298 char *ret;
300 len = centry_uint8(centry);
302 if (len == 0xFF) {
303 /* a deliberate NULL string */
304 return NULL;
307 if (!centry_check_bytes(centry, (size_t)len)) {
308 smb_panic_fn("centry_string");
311 ret = TALLOC_ARRAY(mem_ctx, char, len+1);
312 if (!ret) {
313 smb_panic_fn("centry_string out of memory\n");
315 memcpy(ret,centry->data + centry->ofs, len);
316 ret[len] = 0;
317 centry->ofs += len;
318 return ret;
321 /* pull a hash16 from a cache entry, using the supplied
322 talloc context
324 static char *centry_hash16(struct cache_entry *centry, TALLOC_CTX *mem_ctx)
326 uint32 len;
327 char *ret;
329 len = centry_uint8(centry);
331 if (len != 16) {
332 DEBUG(0,("centry corruption? hash len (%u) != 16\n",
333 len ));
334 return NULL;
337 if (!centry_check_bytes(centry, 16)) {
338 return NULL;
341 ret = TALLOC_ARRAY(mem_ctx, char, 16);
342 if (!ret) {
343 smb_panic_fn("centry_hash out of memory\n");
345 memcpy(ret,centry->data + centry->ofs, 16);
346 centry->ofs += 16;
347 return ret;
350 /* pull a sid from a cache entry, using the supplied
351 talloc context
353 static bool centry_sid(struct cache_entry *centry, struct dom_sid *sid)
355 char *sid_string;
356 bool ret;
358 sid_string = centry_string(centry, talloc_tos());
359 if (sid_string == NULL) {
360 return false;
362 ret = string_to_sid(sid, sid_string);
363 TALLOC_FREE(sid_string);
364 return ret;
369 pull a NTSTATUS from a cache entry
371 static NTSTATUS centry_ntstatus(struct cache_entry *centry)
373 NTSTATUS status;
375 status = NT_STATUS(centry_uint32(centry));
376 return status;
380 /* the server is considered down if it can't give us a sequence number */
381 static bool wcache_server_down(struct winbindd_domain *domain)
383 bool ret;
385 if (!wcache->tdb)
386 return false;
388 ret = (domain->sequence_number == DOM_SEQUENCE_NONE);
390 if (ret)
391 DEBUG(10,("wcache_server_down: server for Domain %s down\n",
392 domain->name ));
393 return ret;
396 static bool wcache_fetch_seqnum(const char *domain_name, uint32_t *seqnum,
397 uint32_t *last_seq_check)
399 char *key;
400 TDB_DATA data;
402 if (wcache->tdb == NULL) {
403 DEBUG(10,("wcache_fetch_seqnum: tdb == NULL\n"));
404 return false;
407 key = talloc_asprintf(talloc_tos(), "SEQNUM/%s", domain_name);
408 if (key == NULL) {
409 DEBUG(10, ("talloc failed\n"));
410 return false;
413 data = tdb_fetch_bystring(wcache->tdb, key);
414 TALLOC_FREE(key);
416 if (data.dptr == NULL) {
417 DEBUG(10, ("wcache_fetch_seqnum: %s not found\n",
418 domain_name));
419 return false;
421 if (data.dsize != 8) {
422 DEBUG(10, ("wcache_fetch_seqnum: invalid data size %d\n",
423 (int)data.dsize));
424 SAFE_FREE(data.dptr);
425 return false;
428 *seqnum = IVAL(data.dptr, 0);
429 *last_seq_check = IVAL(data.dptr, 4);
430 SAFE_FREE(data.dptr);
432 return true;
435 static NTSTATUS fetch_cache_seqnum( struct winbindd_domain *domain, time_t now )
437 uint32 last_check, time_diff;
439 if (!wcache_fetch_seqnum(domain->name, &domain->sequence_number,
440 &last_check)) {
441 return NT_STATUS_UNSUCCESSFUL;
443 domain->last_seq_check = last_check;
445 /* have we expired? */
447 time_diff = now - domain->last_seq_check;
448 if ( time_diff > lp_winbind_cache_time() ) {
449 DEBUG(10,("fetch_cache_seqnum: timeout [%s][%u @ %u]\n",
450 domain->name, domain->sequence_number,
451 (uint32)domain->last_seq_check));
452 return NT_STATUS_UNSUCCESSFUL;
455 DEBUG(10,("fetch_cache_seqnum: success [%s][%u @ %u]\n",
456 domain->name, domain->sequence_number,
457 (uint32)domain->last_seq_check));
459 return NT_STATUS_OK;
462 bool wcache_store_seqnum(const char *domain_name, uint32_t seqnum,
463 time_t last_seq_check)
465 char *key_str;
466 uint8_t buf[8];
467 int ret;
469 if (wcache->tdb == NULL) {
470 DEBUG(10, ("wcache_store_seqnum: wcache->tdb == NULL\n"));
471 return false;
474 key_str = talloc_asprintf(talloc_tos(), "SEQNUM/%s", domain_name);
475 if (key_str == NULL) {
476 DEBUG(10, ("talloc_asprintf failed\n"));
477 return false;
480 SIVAL(buf, 0, seqnum);
481 SIVAL(buf, 4, last_seq_check);
483 ret = tdb_store_bystring(wcache->tdb, key_str,
484 make_tdb_data(buf, sizeof(buf)), TDB_REPLACE);
485 TALLOC_FREE(key_str);
486 if (ret == -1) {
487 DEBUG(10, ("tdb_store_bystring failed: %s\n",
488 tdb_errorstr(wcache->tdb)));
489 TALLOC_FREE(key_str);
490 return false;
493 DEBUG(10, ("wcache_store_seqnum: success [%s][%u @ %u]\n",
494 domain_name, seqnum, (unsigned)last_seq_check));
496 return true;
499 static bool store_cache_seqnum( struct winbindd_domain *domain )
501 return wcache_store_seqnum(domain->name, domain->sequence_number,
502 domain->last_seq_check);
506 refresh the domain sequence number. If force is true
507 then always refresh it, no matter how recently we fetched it
510 static void refresh_sequence_number(struct winbindd_domain *domain, bool force)
512 NTSTATUS status;
513 unsigned time_diff;
514 time_t t = time(NULL);
515 unsigned cache_time = lp_winbind_cache_time();
517 if ( IS_DOMAIN_OFFLINE(domain) ) {
518 return;
521 get_cache( domain );
523 #if 0 /* JERRY -- disable as the default cache time is now 5 minutes */
524 /* trying to reconnect is expensive, don't do it too often */
525 if (domain->sequence_number == DOM_SEQUENCE_NONE) {
526 cache_time *= 8;
528 #endif
530 time_diff = t - domain->last_seq_check;
532 /* see if we have to refetch the domain sequence number */
533 if (!force && (time_diff < cache_time) &&
534 (domain->sequence_number != DOM_SEQUENCE_NONE) &&
535 NT_STATUS_IS_OK(domain->last_status)) {
536 DEBUG(10, ("refresh_sequence_number: %s time ok\n", domain->name));
537 goto done;
540 /* try to get the sequence number from the tdb cache first */
541 /* this will update the timestamp as well */
543 status = fetch_cache_seqnum( domain, t );
544 if (NT_STATUS_IS_OK(status) &&
545 (domain->sequence_number != DOM_SEQUENCE_NONE) &&
546 NT_STATUS_IS_OK(domain->last_status)) {
547 goto done;
550 /* important! make sure that we know if this is a native
551 mode domain or not. And that we can contact it. */
553 if ( winbindd_can_contact_domain( domain ) ) {
554 status = domain->backend->sequence_number(domain,
555 &domain->sequence_number);
556 } else {
557 /* just use the current time */
558 status = NT_STATUS_OK;
559 domain->sequence_number = time(NULL);
563 /* the above call could have set our domain->backend to NULL when
564 * coming from offline to online mode, make sure to reinitialize the
565 * backend - Guenther */
566 get_cache( domain );
568 if (!NT_STATUS_IS_OK(status)) {
569 DEBUG(10,("refresh_sequence_number: failed with %s\n", nt_errstr(status)));
570 domain->sequence_number = DOM_SEQUENCE_NONE;
573 domain->last_status = status;
574 domain->last_seq_check = time(NULL);
576 /* save the new sequence number in the cache */
577 store_cache_seqnum( domain );
579 done:
580 DEBUG(10, ("refresh_sequence_number: %s seq number is now %d\n",
581 domain->name, domain->sequence_number));
583 return;
587 decide if a cache entry has expired
589 static bool centry_expired(struct winbindd_domain *domain, const char *keystr, struct cache_entry *centry)
591 /* If we've been told to be offline - stay in that state... */
592 if (lp_winbind_offline_logon() && global_winbindd_offline_state) {
593 DEBUG(10,("centry_expired: Key %s for domain %s valid as winbindd is globally offline.\n",
594 keystr, domain->name ));
595 return false;
598 /* when the domain is offline return the cached entry.
599 * This deals with transient offline states... */
601 if (!domain->online) {
602 DEBUG(10,("centry_expired: Key %s for domain %s valid as domain is offline.\n",
603 keystr, domain->name ));
604 return false;
607 /* if the server is OK and our cache entry came from when it was down then
608 the entry is invalid */
609 if ((domain->sequence_number != DOM_SEQUENCE_NONE) &&
610 (centry->sequence_number == DOM_SEQUENCE_NONE)) {
611 DEBUG(10,("centry_expired: Key %s for domain %s invalid sequence.\n",
612 keystr, domain->name ));
613 return true;
616 /* if the server is down or the cache entry is not older than the
617 current sequence number then it is OK */
618 if (wcache_server_down(domain) ||
619 centry->sequence_number == domain->sequence_number) {
620 DEBUG(10,("centry_expired: Key %s for domain %s is good.\n",
621 keystr, domain->name ));
622 return false;
625 DEBUG(10,("centry_expired: Key %s for domain %s expired\n",
626 keystr, domain->name ));
628 /* it's expired */
629 return true;
632 static struct cache_entry *wcache_fetch_raw(char *kstr)
634 TDB_DATA data;
635 struct cache_entry *centry;
636 TDB_DATA key;
638 key = string_tdb_data(kstr);
639 data = tdb_fetch(wcache->tdb, key);
640 if (!data.dptr) {
641 /* a cache miss */
642 return NULL;
645 centry = SMB_XMALLOC_P(struct cache_entry);
646 centry->data = (unsigned char *)data.dptr;
647 centry->len = data.dsize;
648 centry->ofs = 0;
650 if (centry->len < 8) {
651 /* huh? corrupt cache? */
652 DEBUG(10,("wcache_fetch_raw: Corrupt cache for key %s (len < 8) ?\n", kstr));
653 centry_free(centry);
654 return NULL;
657 centry->status = centry_ntstatus(centry);
658 centry->sequence_number = centry_uint32(centry);
660 return centry;
664 fetch an entry from the cache, with a varargs key. auto-fetch the sequence
665 number and return status
667 static struct cache_entry *wcache_fetch(struct winbind_cache *cache,
668 struct winbindd_domain *domain,
669 const char *format, ...) PRINTF_ATTRIBUTE(3,4);
670 static struct cache_entry *wcache_fetch(struct winbind_cache *cache,
671 struct winbindd_domain *domain,
672 const char *format, ...)
674 va_list ap;
675 char *kstr;
676 struct cache_entry *centry;
678 if (!winbindd_use_cache()) {
679 return NULL;
682 refresh_sequence_number(domain, false);
684 va_start(ap, format);
685 smb_xvasprintf(&kstr, format, ap);
686 va_end(ap);
688 centry = wcache_fetch_raw(kstr);
689 if (centry == NULL) {
690 free(kstr);
691 return NULL;
694 if (centry_expired(domain, kstr, centry)) {
696 DEBUG(10,("wcache_fetch: entry %s expired for domain %s\n",
697 kstr, domain->name ));
699 centry_free(centry);
700 free(kstr);
701 return NULL;
704 DEBUG(10,("wcache_fetch: returning entry %s for domain %s\n",
705 kstr, domain->name ));
707 free(kstr);
708 return centry;
711 static void wcache_delete(const char *format, ...) PRINTF_ATTRIBUTE(1,2);
712 static void wcache_delete(const char *format, ...)
714 va_list ap;
715 char *kstr;
716 TDB_DATA key;
718 va_start(ap, format);
719 smb_xvasprintf(&kstr, format, ap);
720 va_end(ap);
722 key = string_tdb_data(kstr);
724 tdb_delete(wcache->tdb, key);
725 free(kstr);
729 make sure we have at least len bytes available in a centry
731 static void centry_expand(struct cache_entry *centry, uint32 len)
733 if (centry->len - centry->ofs >= len)
734 return;
735 centry->len *= 2;
736 centry->data = SMB_REALLOC_ARRAY(centry->data, unsigned char,
737 centry->len);
738 if (!centry->data) {
739 DEBUG(0,("out of memory: needed %d bytes in centry_expand\n", centry->len));
740 smb_panic_fn("out of memory in centry_expand");
745 push a uint32 into a centry
747 static void centry_put_uint32(struct cache_entry *centry, uint32 v)
749 centry_expand(centry, 4);
750 SIVAL(centry->data, centry->ofs, v);
751 centry->ofs += 4;
755 push a uint16 into a centry
757 static void centry_put_uint16(struct cache_entry *centry, uint16 v)
759 centry_expand(centry, 2);
760 SIVAL(centry->data, centry->ofs, v);
761 centry->ofs += 2;
765 push a uint8 into a centry
767 static void centry_put_uint8(struct cache_entry *centry, uint8 v)
769 centry_expand(centry, 1);
770 SCVAL(centry->data, centry->ofs, v);
771 centry->ofs += 1;
775 push a string into a centry
777 static void centry_put_string(struct cache_entry *centry, const char *s)
779 int len;
781 if (!s) {
782 /* null strings are marked as len 0xFFFF */
783 centry_put_uint8(centry, 0xFF);
784 return;
787 len = strlen(s);
788 /* can't handle more than 254 char strings. Truncating is probably best */
789 if (len > 254) {
790 DEBUG(10,("centry_put_string: truncating len (%d) to: 254\n", len));
791 len = 254;
793 centry_put_uint8(centry, len);
794 centry_expand(centry, len);
795 memcpy(centry->data + centry->ofs, s, len);
796 centry->ofs += len;
800 push a 16 byte hash into a centry - treat as 16 byte string.
802 static void centry_put_hash16(struct cache_entry *centry, const uint8 val[16])
804 centry_put_uint8(centry, 16);
805 centry_expand(centry, 16);
806 memcpy(centry->data + centry->ofs, val, 16);
807 centry->ofs += 16;
810 static void centry_put_sid(struct cache_entry *centry, const DOM_SID *sid)
812 fstring sid_string;
813 centry_put_string(centry, sid_to_fstring(sid_string, sid));
818 put NTSTATUS into a centry
820 static void centry_put_ntstatus(struct cache_entry *centry, NTSTATUS status)
822 uint32 status_value = NT_STATUS_V(status);
823 centry_put_uint32(centry, status_value);
828 push a NTTIME into a centry
830 static void centry_put_nttime(struct cache_entry *centry, NTTIME nt)
832 centry_expand(centry, 8);
833 SIVAL(centry->data, centry->ofs, nt & 0xFFFFFFFF);
834 centry->ofs += 4;
835 SIVAL(centry->data, centry->ofs, nt >> 32);
836 centry->ofs += 4;
840 push a time_t into a centry - use a 64 bit size.
841 NTTIME here is being used as a convenient 64-bit size.
843 static void centry_put_time(struct cache_entry *centry, time_t t)
845 NTTIME nt = (NTTIME)t;
846 centry_put_nttime(centry, nt);
850 start a centry for output. When finished, call centry_end()
852 struct cache_entry *centry_start(struct winbindd_domain *domain, NTSTATUS status)
854 struct cache_entry *centry;
856 if (!wcache->tdb)
857 return NULL;
859 centry = SMB_XMALLOC_P(struct cache_entry);
861 centry->len = 8192; /* reasonable default */
862 centry->data = SMB_XMALLOC_ARRAY(uint8, centry->len);
863 centry->ofs = 0;
864 centry->sequence_number = domain->sequence_number;
865 centry_put_ntstatus(centry, status);
866 centry_put_uint32(centry, centry->sequence_number);
867 return centry;
871 finish a centry and write it to the tdb
873 static void centry_end(struct cache_entry *centry, const char *format, ...) PRINTF_ATTRIBUTE(2,3);
874 static void centry_end(struct cache_entry *centry, const char *format, ...)
876 va_list ap;
877 char *kstr;
878 TDB_DATA key, data;
880 if (!winbindd_use_cache()) {
881 return;
884 va_start(ap, format);
885 smb_xvasprintf(&kstr, format, ap);
886 va_end(ap);
888 key = string_tdb_data(kstr);
889 data.dptr = centry->data;
890 data.dsize = centry->ofs;
892 tdb_store(wcache->tdb, key, data, TDB_REPLACE);
893 free(kstr);
896 static void wcache_save_name_to_sid(struct winbindd_domain *domain,
897 NTSTATUS status, const char *domain_name,
898 const char *name, const DOM_SID *sid,
899 enum lsa_SidType type)
901 struct cache_entry *centry;
902 fstring uname;
904 centry = centry_start(domain, status);
905 if (!centry)
906 return;
907 centry_put_uint32(centry, type);
908 centry_put_sid(centry, sid);
909 fstrcpy(uname, name);
910 strupper_m(uname);
911 centry_end(centry, "NS/%s/%s", domain_name, uname);
912 DEBUG(10,("wcache_save_name_to_sid: %s\\%s -> %s (%s)\n", domain_name,
913 uname, sid_string_dbg(sid), nt_errstr(status)));
914 centry_free(centry);
917 static void wcache_save_sid_to_name(struct winbindd_domain *domain, NTSTATUS status,
918 const DOM_SID *sid, const char *domain_name, const char *name, enum lsa_SidType type)
920 struct cache_entry *centry;
921 fstring sid_string;
923 centry = centry_start(domain, status);
924 if (!centry)
925 return;
927 if (NT_STATUS_IS_OK(status)) {
928 centry_put_uint32(centry, type);
929 centry_put_string(centry, domain_name);
930 centry_put_string(centry, name);
933 centry_end(centry, "SN/%s", sid_to_fstring(sid_string, sid));
934 DEBUG(10,("wcache_save_sid_to_name: %s -> %s (%s)\n", sid_string,
935 name, nt_errstr(status)));
936 centry_free(centry);
940 static void wcache_save_user(struct winbindd_domain *domain, NTSTATUS status,
941 struct wbint_userinfo *info)
943 struct cache_entry *centry;
944 fstring sid_string;
946 if (is_null_sid(&info->user_sid)) {
947 return;
950 centry = centry_start(domain, status);
951 if (!centry)
952 return;
953 centry_put_string(centry, info->acct_name);
954 centry_put_string(centry, info->full_name);
955 centry_put_string(centry, info->homedir);
956 centry_put_string(centry, info->shell);
957 centry_put_uint32(centry, info->primary_gid);
958 centry_put_sid(centry, &info->user_sid);
959 centry_put_sid(centry, &info->group_sid);
960 centry_end(centry, "U/%s", sid_to_fstring(sid_string,
961 &info->user_sid));
962 DEBUG(10,("wcache_save_user: %s (acct_name %s)\n", sid_string, info->acct_name));
963 centry_free(centry);
966 static void wcache_save_lockout_policy(struct winbindd_domain *domain,
967 NTSTATUS status,
968 struct samr_DomInfo12 *lockout_policy)
970 struct cache_entry *centry;
972 centry = centry_start(domain, status);
973 if (!centry)
974 return;
976 centry_put_nttime(centry, lockout_policy->lockout_duration);
977 centry_put_nttime(centry, lockout_policy->lockout_window);
978 centry_put_uint16(centry, lockout_policy->lockout_threshold);
980 centry_end(centry, "LOC_POL/%s", domain->name);
982 DEBUG(10,("wcache_save_lockout_policy: %s\n", domain->name));
984 centry_free(centry);
989 static void wcache_save_password_policy(struct winbindd_domain *domain,
990 NTSTATUS status,
991 struct samr_DomInfo1 *policy)
993 struct cache_entry *centry;
995 centry = centry_start(domain, status);
996 if (!centry)
997 return;
999 centry_put_uint16(centry, policy->min_password_length);
1000 centry_put_uint16(centry, policy->password_history_length);
1001 centry_put_uint32(centry, policy->password_properties);
1002 centry_put_nttime(centry, policy->max_password_age);
1003 centry_put_nttime(centry, policy->min_password_age);
1005 centry_end(centry, "PWD_POL/%s", domain->name);
1007 DEBUG(10,("wcache_save_password_policy: %s\n", domain->name));
1009 centry_free(centry);
1012 /***************************************************************************
1013 ***************************************************************************/
1015 static void wcache_save_username_alias(struct winbindd_domain *domain,
1016 NTSTATUS status,
1017 const char *name, const char *alias)
1019 struct cache_entry *centry;
1020 fstring uname;
1022 if ( (centry = centry_start(domain, status)) == NULL )
1023 return;
1025 centry_put_string( centry, alias );
1027 fstrcpy(uname, name);
1028 strupper_m(uname);
1029 centry_end(centry, "NSS/NA/%s", uname);
1031 DEBUG(10,("wcache_save_username_alias: %s -> %s\n", name, alias ));
1033 centry_free(centry);
1036 static void wcache_save_alias_username(struct winbindd_domain *domain,
1037 NTSTATUS status,
1038 const char *alias, const char *name)
1040 struct cache_entry *centry;
1041 fstring uname;
1043 if ( (centry = centry_start(domain, status)) == NULL )
1044 return;
1046 centry_put_string( centry, name );
1048 fstrcpy(uname, alias);
1049 strupper_m(uname);
1050 centry_end(centry, "NSS/AN/%s", uname);
1052 DEBUG(10,("wcache_save_alias_username: %s -> %s\n", alias, name ));
1054 centry_free(centry);
1057 /***************************************************************************
1058 ***************************************************************************/
1060 NTSTATUS resolve_username_to_alias( TALLOC_CTX *mem_ctx,
1061 struct winbindd_domain *domain,
1062 const char *name, char **alias )
1064 struct winbind_cache *cache = get_cache(domain);
1065 struct cache_entry *centry = NULL;
1066 NTSTATUS status;
1067 char *upper_name;
1069 if ( domain->internal )
1070 return NT_STATUS_NOT_SUPPORTED;
1072 if (!cache->tdb)
1073 goto do_query;
1075 if ( (upper_name = SMB_STRDUP(name)) == NULL )
1076 return NT_STATUS_NO_MEMORY;
1077 strupper_m(upper_name);
1079 centry = wcache_fetch(cache, domain, "NSS/NA/%s", upper_name);
1081 SAFE_FREE( upper_name );
1083 if (!centry)
1084 goto do_query;
1086 status = centry->status;
1088 if (!NT_STATUS_IS_OK(status)) {
1089 centry_free(centry);
1090 return status;
1093 *alias = centry_string( centry, mem_ctx );
1095 centry_free(centry);
1097 DEBUG(10,("resolve_username_to_alias: [Cached] - mapped %s to %s\n",
1098 name, *alias ? *alias : "(none)"));
1100 return (*alias) ? NT_STATUS_OK : NT_STATUS_OBJECT_NAME_NOT_FOUND;
1102 do_query:
1104 /* If its not in cache and we are offline, then fail */
1106 if ( get_global_winbindd_state_offline() || !domain->online ) {
1107 DEBUG(8,("resolve_username_to_alias: rejecting query "
1108 "in offline mode\n"));
1109 return NT_STATUS_NOT_FOUND;
1112 status = nss_map_to_alias( mem_ctx, domain->name, name, alias );
1114 if ( NT_STATUS_IS_OK( status ) ) {
1115 wcache_save_username_alias(domain, status, name, *alias);
1118 if ( NT_STATUS_EQUAL( status, NT_STATUS_NONE_MAPPED ) ) {
1119 wcache_save_username_alias(domain, status, name, "(NULL)");
1122 DEBUG(5,("resolve_username_to_alias: backend query returned %s\n",
1123 nt_errstr(status)));
1125 if ( NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ) {
1126 set_domain_offline( domain );
1129 return status;
1132 /***************************************************************************
1133 ***************************************************************************/
1135 NTSTATUS resolve_alias_to_username( TALLOC_CTX *mem_ctx,
1136 struct winbindd_domain *domain,
1137 const char *alias, char **name )
1139 struct winbind_cache *cache = get_cache(domain);
1140 struct cache_entry *centry = NULL;
1141 NTSTATUS status;
1142 char *upper_name;
1144 if ( domain->internal )
1145 return NT_STATUS_NOT_SUPPORTED;
1147 if (!cache->tdb)
1148 goto do_query;
1150 if ( (upper_name = SMB_STRDUP(alias)) == NULL )
1151 return NT_STATUS_NO_MEMORY;
1152 strupper_m(upper_name);
1154 centry = wcache_fetch(cache, domain, "NSS/AN/%s", upper_name);
1156 SAFE_FREE( upper_name );
1158 if (!centry)
1159 goto do_query;
1161 status = centry->status;
1163 if (!NT_STATUS_IS_OK(status)) {
1164 centry_free(centry);
1165 return status;
1168 *name = centry_string( centry, mem_ctx );
1170 centry_free(centry);
1172 DEBUG(10,("resolve_alias_to_username: [Cached] - mapped %s to %s\n",
1173 alias, *name ? *name : "(none)"));
1175 return (*name) ? NT_STATUS_OK : NT_STATUS_OBJECT_NAME_NOT_FOUND;
1177 do_query:
1179 /* If its not in cache and we are offline, then fail */
1181 if ( get_global_winbindd_state_offline() || !domain->online ) {
1182 DEBUG(8,("resolve_alias_to_username: rejecting query "
1183 "in offline mode\n"));
1184 return NT_STATUS_NOT_FOUND;
1187 /* an alias cannot contain a domain prefix or '@' */
1189 if (strchr(alias, '\\') || strchr(alias, '@')) {
1190 DEBUG(10,("resolve_alias_to_username: skipping fully "
1191 "qualified name %s\n", alias));
1192 return NT_STATUS_OBJECT_NAME_INVALID;
1195 status = nss_map_from_alias( mem_ctx, domain->name, alias, name );
1197 if ( NT_STATUS_IS_OK( status ) ) {
1198 wcache_save_alias_username( domain, status, alias, *name );
1201 if (NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED)) {
1202 wcache_save_alias_username(domain, status, alias, "(NULL)");
1205 DEBUG(5,("resolve_alias_to_username: backend query returned %s\n",
1206 nt_errstr(status)));
1208 if ( NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ) {
1209 set_domain_offline( domain );
1212 return status;
1215 NTSTATUS wcache_cached_creds_exist(struct winbindd_domain *domain, const DOM_SID *sid)
1217 struct winbind_cache *cache = get_cache(domain);
1218 TDB_DATA data;
1219 fstring key_str, tmp;
1220 uint32 rid;
1222 if (!cache->tdb) {
1223 return NT_STATUS_INTERNAL_DB_ERROR;
1226 if (is_null_sid(sid)) {
1227 return NT_STATUS_INVALID_SID;
1230 if (!(sid_peek_rid(sid, &rid)) || (rid == 0)) {
1231 return NT_STATUS_INVALID_SID;
1234 fstr_sprintf(key_str, "CRED/%s", sid_to_fstring(tmp, sid));
1236 data = tdb_fetch(cache->tdb, string_tdb_data(key_str));
1237 if (!data.dptr) {
1238 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1241 SAFE_FREE(data.dptr);
1242 return NT_STATUS_OK;
1245 /* Lookup creds for a SID - copes with old (unsalted) creds as well
1246 as new salted ones. */
1248 NTSTATUS wcache_get_creds(struct winbindd_domain *domain,
1249 TALLOC_CTX *mem_ctx,
1250 const DOM_SID *sid,
1251 const uint8 **cached_nt_pass,
1252 const uint8 **cached_salt)
1254 struct winbind_cache *cache = get_cache(domain);
1255 struct cache_entry *centry = NULL;
1256 NTSTATUS status;
1257 time_t t;
1258 uint32 rid;
1259 fstring tmp;
1261 if (!cache->tdb) {
1262 return NT_STATUS_INTERNAL_DB_ERROR;
1265 if (is_null_sid(sid)) {
1266 return NT_STATUS_INVALID_SID;
1269 if (!(sid_peek_rid(sid, &rid)) || (rid == 0)) {
1270 return NT_STATUS_INVALID_SID;
1273 /* Try and get a salted cred first. If we can't
1274 fall back to an unsalted cred. */
1276 centry = wcache_fetch(cache, domain, "CRED/%s",
1277 sid_to_fstring(tmp, sid));
1278 if (!centry) {
1279 DEBUG(10,("wcache_get_creds: entry for [CRED/%s] not found\n",
1280 sid_string_dbg(sid)));
1281 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1284 t = centry_time(centry);
1286 /* In the salted case this isn't actually the nt_hash itself,
1287 but the MD5 of the salt + nt_hash. Let the caller
1288 sort this out. It can tell as we only return the cached_salt
1289 if we are returning a salted cred. */
1291 *cached_nt_pass = (const uint8 *)centry_hash16(centry, mem_ctx);
1292 if (*cached_nt_pass == NULL) {
1293 fstring sidstr;
1295 sid_to_fstring(sidstr, sid);
1297 /* Bad (old) cred cache. Delete and pretend we
1298 don't have it. */
1299 DEBUG(0,("wcache_get_creds: bad entry for [CRED/%s] - deleting\n",
1300 sidstr));
1301 wcache_delete("CRED/%s", sidstr);
1302 centry_free(centry);
1303 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1306 /* We only have 17 bytes more data in the salted cred case. */
1307 if (centry->len - centry->ofs == 17) {
1308 *cached_salt = (const uint8 *)centry_hash16(centry, mem_ctx);
1309 } else {
1310 *cached_salt = NULL;
1313 dump_data_pw("cached_nt_pass", *cached_nt_pass, NT_HASH_LEN);
1314 if (*cached_salt) {
1315 dump_data_pw("cached_salt", *cached_salt, NT_HASH_LEN);
1318 status = centry->status;
1320 DEBUG(10,("wcache_get_creds: [Cached] - cached creds for user %s status: %s\n",
1321 sid_string_dbg(sid), nt_errstr(status) ));
1323 centry_free(centry);
1324 return status;
1327 /* Store creds for a SID - only writes out new salted ones. */
1329 NTSTATUS wcache_save_creds(struct winbindd_domain *domain,
1330 TALLOC_CTX *mem_ctx,
1331 const DOM_SID *sid,
1332 const uint8 nt_pass[NT_HASH_LEN])
1334 struct cache_entry *centry;
1335 fstring sid_string;
1336 uint32 rid;
1337 uint8 cred_salt[NT_HASH_LEN];
1338 uint8 salted_hash[NT_HASH_LEN];
1340 if (is_null_sid(sid)) {
1341 return NT_STATUS_INVALID_SID;
1344 if (!(sid_peek_rid(sid, &rid)) || (rid == 0)) {
1345 return NT_STATUS_INVALID_SID;
1348 centry = centry_start(domain, NT_STATUS_OK);
1349 if (!centry) {
1350 return NT_STATUS_INTERNAL_DB_ERROR;
1353 dump_data_pw("nt_pass", nt_pass, NT_HASH_LEN);
1355 centry_put_time(centry, time(NULL));
1357 /* Create a salt and then salt the hash. */
1358 generate_random_buffer(cred_salt, NT_HASH_LEN);
1359 E_md5hash(cred_salt, nt_pass, salted_hash);
1361 centry_put_hash16(centry, salted_hash);
1362 centry_put_hash16(centry, cred_salt);
1363 centry_end(centry, "CRED/%s", sid_to_fstring(sid_string, sid));
1365 DEBUG(10,("wcache_save_creds: %s\n", sid_string));
1367 centry_free(centry);
1369 return NT_STATUS_OK;
1373 /* Query display info. This is the basic user list fn */
1374 static NTSTATUS query_user_list(struct winbindd_domain *domain,
1375 TALLOC_CTX *mem_ctx,
1376 uint32 *num_entries,
1377 struct wbint_userinfo **info)
1379 struct winbind_cache *cache = get_cache(domain);
1380 struct cache_entry *centry = NULL;
1381 NTSTATUS status;
1382 unsigned int i, retry;
1384 if (!cache->tdb)
1385 goto do_query;
1387 centry = wcache_fetch(cache, domain, "UL/%s", domain->name);
1388 if (!centry)
1389 goto do_query;
1391 *num_entries = centry_uint32(centry);
1393 if (*num_entries == 0)
1394 goto do_cached;
1396 (*info) = TALLOC_ARRAY(mem_ctx, struct wbint_userinfo, *num_entries);
1397 if (! (*info)) {
1398 smb_panic_fn("query_user_list out of memory");
1400 for (i=0; i<(*num_entries); i++) {
1401 (*info)[i].acct_name = centry_string(centry, mem_ctx);
1402 (*info)[i].full_name = centry_string(centry, mem_ctx);
1403 (*info)[i].homedir = centry_string(centry, mem_ctx);
1404 (*info)[i].shell = centry_string(centry, mem_ctx);
1405 centry_sid(centry, &(*info)[i].user_sid);
1406 centry_sid(centry, &(*info)[i].group_sid);
1409 do_cached:
1410 status = centry->status;
1412 DEBUG(10,("query_user_list: [Cached] - cached list for domain %s status: %s\n",
1413 domain->name, nt_errstr(status) ));
1415 centry_free(centry);
1416 return status;
1418 do_query:
1419 *num_entries = 0;
1420 *info = NULL;
1422 /* Return status value returned by seq number check */
1424 if (!NT_STATUS_IS_OK(domain->last_status))
1425 return domain->last_status;
1427 /* Put the query_user_list() in a retry loop. There appears to be
1428 * some bug either with Windows 2000 or Samba's handling of large
1429 * rpc replies. This manifests itself as sudden disconnection
1430 * at a random point in the enumeration of a large (60k) user list.
1431 * The retry loop simply tries the operation again. )-: It's not
1432 * pretty but an acceptable workaround until we work out what the
1433 * real problem is. */
1435 retry = 0;
1436 do {
1438 DEBUG(10,("query_user_list: [Cached] - doing backend query for list for domain %s\n",
1439 domain->name ));
1441 status = domain->backend->query_user_list(domain, mem_ctx, num_entries, info);
1442 if (!NT_STATUS_IS_OK(status)) {
1443 DEBUG(3, ("query_user_list: returned 0x%08x, "
1444 "retrying\n", NT_STATUS_V(status)));
1446 if (NT_STATUS_EQUAL(status, NT_STATUS_UNSUCCESSFUL)) {
1447 DEBUG(3, ("query_user_list: flushing "
1448 "connection cache\n"));
1449 invalidate_cm_connection(&domain->conn);
1452 } while (NT_STATUS_V(status) == NT_STATUS_V(NT_STATUS_UNSUCCESSFUL) &&
1453 (retry++ < 5));
1455 /* and save it */
1456 refresh_sequence_number(domain, false);
1457 centry = centry_start(domain, status);
1458 if (!centry)
1459 goto skip_save;
1460 centry_put_uint32(centry, *num_entries);
1461 for (i=0; i<(*num_entries); i++) {
1462 centry_put_string(centry, (*info)[i].acct_name);
1463 centry_put_string(centry, (*info)[i].full_name);
1464 centry_put_string(centry, (*info)[i].homedir);
1465 centry_put_string(centry, (*info)[i].shell);
1466 centry_put_sid(centry, &(*info)[i].user_sid);
1467 centry_put_sid(centry, &(*info)[i].group_sid);
1468 if (domain->backend && domain->backend->consistent) {
1469 /* when the backend is consistent we can pre-prime some mappings */
1470 wcache_save_name_to_sid(domain, NT_STATUS_OK,
1471 domain->name,
1472 (*info)[i].acct_name,
1473 &(*info)[i].user_sid,
1474 SID_NAME_USER);
1475 wcache_save_sid_to_name(domain, NT_STATUS_OK,
1476 &(*info)[i].user_sid,
1477 domain->name,
1478 (*info)[i].acct_name,
1479 SID_NAME_USER);
1480 wcache_save_user(domain, NT_STATUS_OK, &(*info)[i]);
1483 centry_end(centry, "UL/%s", domain->name);
1484 centry_free(centry);
1486 skip_save:
1487 return status;
1490 /* list all domain groups */
1491 static NTSTATUS enum_dom_groups(struct winbindd_domain *domain,
1492 TALLOC_CTX *mem_ctx,
1493 uint32 *num_entries,
1494 struct acct_info **info)
1496 struct winbind_cache *cache = get_cache(domain);
1497 struct cache_entry *centry = NULL;
1498 NTSTATUS status;
1499 unsigned int i;
1501 if (!cache->tdb)
1502 goto do_query;
1504 centry = wcache_fetch(cache, domain, "GL/%s/domain", domain->name);
1505 if (!centry)
1506 goto do_query;
1508 *num_entries = centry_uint32(centry);
1510 if (*num_entries == 0)
1511 goto do_cached;
1513 (*info) = TALLOC_ARRAY(mem_ctx, struct acct_info, *num_entries);
1514 if (! (*info)) {
1515 smb_panic_fn("enum_dom_groups out of memory");
1517 for (i=0; i<(*num_entries); i++) {
1518 fstrcpy((*info)[i].acct_name, centry_string(centry, mem_ctx));
1519 fstrcpy((*info)[i].acct_desc, centry_string(centry, mem_ctx));
1520 (*info)[i].rid = centry_uint32(centry);
1523 do_cached:
1524 status = centry->status;
1526 DEBUG(10,("enum_dom_groups: [Cached] - cached list for domain %s status: %s\n",
1527 domain->name, nt_errstr(status) ));
1529 centry_free(centry);
1530 return status;
1532 do_query:
1533 *num_entries = 0;
1534 *info = NULL;
1536 /* Return status value returned by seq number check */
1538 if (!NT_STATUS_IS_OK(domain->last_status))
1539 return domain->last_status;
1541 DEBUG(10,("enum_dom_groups: [Cached] - doing backend query for list for domain %s\n",
1542 domain->name ));
1544 status = domain->backend->enum_dom_groups(domain, mem_ctx, num_entries, info);
1546 /* and save it */
1547 refresh_sequence_number(domain, false);
1548 centry = centry_start(domain, status);
1549 if (!centry)
1550 goto skip_save;
1551 centry_put_uint32(centry, *num_entries);
1552 for (i=0; i<(*num_entries); i++) {
1553 centry_put_string(centry, (*info)[i].acct_name);
1554 centry_put_string(centry, (*info)[i].acct_desc);
1555 centry_put_uint32(centry, (*info)[i].rid);
1557 centry_end(centry, "GL/%s/domain", domain->name);
1558 centry_free(centry);
1560 skip_save:
1561 return status;
1564 /* list all domain groups */
1565 static NTSTATUS enum_local_groups(struct winbindd_domain *domain,
1566 TALLOC_CTX *mem_ctx,
1567 uint32 *num_entries,
1568 struct acct_info **info)
1570 struct winbind_cache *cache = get_cache(domain);
1571 struct cache_entry *centry = NULL;
1572 NTSTATUS status;
1573 unsigned int i;
1575 if (!cache->tdb)
1576 goto do_query;
1578 centry = wcache_fetch(cache, domain, "GL/%s/local", domain->name);
1579 if (!centry)
1580 goto do_query;
1582 *num_entries = centry_uint32(centry);
1584 if (*num_entries == 0)
1585 goto do_cached;
1587 (*info) = TALLOC_ARRAY(mem_ctx, struct acct_info, *num_entries);
1588 if (! (*info)) {
1589 smb_panic_fn("enum_dom_groups out of memory");
1591 for (i=0; i<(*num_entries); i++) {
1592 fstrcpy((*info)[i].acct_name, centry_string(centry, mem_ctx));
1593 fstrcpy((*info)[i].acct_desc, centry_string(centry, mem_ctx));
1594 (*info)[i].rid = centry_uint32(centry);
1597 do_cached:
1599 /* If we are returning cached data and the domain controller
1600 is down then we don't know whether the data is up to date
1601 or not. Return NT_STATUS_MORE_PROCESSING_REQUIRED to
1602 indicate this. */
1604 if (wcache_server_down(domain)) {
1605 DEBUG(10, ("enum_local_groups: returning cached user list and server was down\n"));
1606 status = NT_STATUS_MORE_PROCESSING_REQUIRED;
1607 } else
1608 status = centry->status;
1610 DEBUG(10,("enum_local_groups: [Cached] - cached list for domain %s status: %s\n",
1611 domain->name, nt_errstr(status) ));
1613 centry_free(centry);
1614 return status;
1616 do_query:
1617 *num_entries = 0;
1618 *info = NULL;
1620 /* Return status value returned by seq number check */
1622 if (!NT_STATUS_IS_OK(domain->last_status))
1623 return domain->last_status;
1625 DEBUG(10,("enum_local_groups: [Cached] - doing backend query for list for domain %s\n",
1626 domain->name ));
1628 status = domain->backend->enum_local_groups(domain, mem_ctx, num_entries, info);
1630 /* and save it */
1631 refresh_sequence_number(domain, false);
1632 centry = centry_start(domain, status);
1633 if (!centry)
1634 goto skip_save;
1635 centry_put_uint32(centry, *num_entries);
1636 for (i=0; i<(*num_entries); i++) {
1637 centry_put_string(centry, (*info)[i].acct_name);
1638 centry_put_string(centry, (*info)[i].acct_desc);
1639 centry_put_uint32(centry, (*info)[i].rid);
1641 centry_end(centry, "GL/%s/local", domain->name);
1642 centry_free(centry);
1644 skip_save:
1645 return status;
1648 NTSTATUS wcache_name_to_sid(struct winbindd_domain *domain,
1649 const char *domain_name,
1650 const char *name,
1651 struct dom_sid *sid,
1652 enum lsa_SidType *type)
1654 struct winbind_cache *cache = get_cache(domain);
1655 struct cache_entry *centry;
1656 NTSTATUS status;
1657 char *uname;
1659 if (cache->tdb == NULL) {
1660 return NT_STATUS_NOT_FOUND;
1663 uname = talloc_strdup_upper(talloc_tos(), name);
1664 if (uname == NULL) {
1665 return NT_STATUS_NO_MEMORY;
1668 centry = wcache_fetch(cache, domain, "NS/%s/%s", domain_name, uname);
1669 TALLOC_FREE(uname);
1670 if (centry == NULL) {
1671 return NT_STATUS_NOT_FOUND;
1674 status = centry->status;
1675 if (NT_STATUS_IS_OK(status)) {
1676 *type = (enum lsa_SidType)centry_uint32(centry);
1677 centry_sid(centry, sid);
1680 DEBUG(10,("name_to_sid: [Cached] - cached name for domain %s status: "
1681 "%s\n", domain->name, nt_errstr(status) ));
1683 centry_free(centry);
1684 return status;
1687 /* convert a single name to a sid in a domain */
1688 static NTSTATUS name_to_sid(struct winbindd_domain *domain,
1689 TALLOC_CTX *mem_ctx,
1690 const char *domain_name,
1691 const char *name,
1692 uint32_t flags,
1693 DOM_SID *sid,
1694 enum lsa_SidType *type)
1696 NTSTATUS status;
1698 status = wcache_name_to_sid(domain, domain_name, name, sid, type);
1699 if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1700 return status;
1703 ZERO_STRUCTP(sid);
1705 /* If the seq number check indicated that there is a problem
1706 * with this DC, then return that status... except for
1707 * access_denied. This is special because the dc may be in
1708 * "restrict anonymous = 1" mode, in which case it will deny
1709 * most unauthenticated operations, but *will* allow the LSA
1710 * name-to-sid that we try as a fallback. */
1712 if (!(NT_STATUS_IS_OK(domain->last_status)
1713 || NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED)))
1714 return domain->last_status;
1716 DEBUG(10,("name_to_sid: [Cached] - doing backend query for name for domain %s\n",
1717 domain->name ));
1719 status = domain->backend->name_to_sid(domain, mem_ctx, domain_name,
1720 name, flags, sid, type);
1722 /* and save it */
1723 refresh_sequence_number(domain, false);
1725 if (domain->online &&
1726 (NT_STATUS_IS_OK(status) || NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED))) {
1727 wcache_save_name_to_sid(domain, status, domain_name, name, sid, *type);
1729 /* Only save the reverse mapping if this was not a UPN */
1730 if (!strchr(name, '@')) {
1731 strupper_m(CONST_DISCARD(char *,domain_name));
1732 strlower_m(CONST_DISCARD(char *,name));
1733 wcache_save_sid_to_name(domain, status, sid, domain_name, name, *type);
1737 return status;
1740 NTSTATUS wcache_sid_to_name(struct winbindd_domain *domain,
1741 const struct dom_sid *sid,
1742 TALLOC_CTX *mem_ctx,
1743 char **domain_name,
1744 char **name,
1745 enum lsa_SidType *type)
1747 struct winbind_cache *cache = get_cache(domain);
1748 struct cache_entry *centry;
1749 char *sid_string;
1750 NTSTATUS status;
1752 if (cache->tdb == NULL) {
1753 return NT_STATUS_NOT_FOUND;
1756 sid_string = sid_string_tos(sid);
1757 if (sid_string == NULL) {
1758 return NT_STATUS_NO_MEMORY;
1761 centry = wcache_fetch(cache, domain, "SN/%s", sid_string);
1762 TALLOC_FREE(sid_string);
1763 if (centry == NULL) {
1764 return NT_STATUS_NOT_FOUND;
1767 if (NT_STATUS_IS_OK(centry->status)) {
1768 *type = (enum lsa_SidType)centry_uint32(centry);
1769 *domain_name = centry_string(centry, mem_ctx);
1770 *name = centry_string(centry, mem_ctx);
1773 status = centry->status;
1774 centry_free(centry);
1776 DEBUG(10,("sid_to_name: [Cached] - cached name for domain %s status: "
1777 "%s\n", domain->name, nt_errstr(status) ));
1779 return status;
1782 /* convert a sid to a user or group name. The sid is guaranteed to be in the domain
1783 given */
1784 static NTSTATUS sid_to_name(struct winbindd_domain *domain,
1785 TALLOC_CTX *mem_ctx,
1786 const DOM_SID *sid,
1787 char **domain_name,
1788 char **name,
1789 enum lsa_SidType *type)
1791 NTSTATUS status;
1793 status = wcache_sid_to_name(domain, sid, mem_ctx, domain_name, name,
1794 type);
1795 if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1796 return status;
1799 *name = NULL;
1800 *domain_name = NULL;
1802 /* If the seq number check indicated that there is a problem
1803 * with this DC, then return that status... except for
1804 * access_denied. This is special because the dc may be in
1805 * "restrict anonymous = 1" mode, in which case it will deny
1806 * most unauthenticated operations, but *will* allow the LSA
1807 * sid-to-name that we try as a fallback. */
1809 if (!(NT_STATUS_IS_OK(domain->last_status)
1810 || NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED)))
1811 return domain->last_status;
1813 DEBUG(10,("sid_to_name: [Cached] - doing backend query for name for domain %s\n",
1814 domain->name ));
1816 status = domain->backend->sid_to_name(domain, mem_ctx, sid, domain_name, name, type);
1818 /* and save it */
1819 refresh_sequence_number(domain, false);
1820 wcache_save_sid_to_name(domain, status, sid, *domain_name, *name, *type);
1822 /* We can't save the name to sid mapping here, as with sid history a
1823 * later name2sid would give the wrong sid. */
1825 return status;
1828 static NTSTATUS rids_to_names(struct winbindd_domain *domain,
1829 TALLOC_CTX *mem_ctx,
1830 const DOM_SID *domain_sid,
1831 uint32 *rids,
1832 size_t num_rids,
1833 char **domain_name,
1834 char ***names,
1835 enum lsa_SidType **types)
1837 struct winbind_cache *cache = get_cache(domain);
1838 size_t i;
1839 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1840 bool have_mapped;
1841 bool have_unmapped;
1843 *domain_name = NULL;
1844 *names = NULL;
1845 *types = NULL;
1847 if (!cache->tdb) {
1848 goto do_query;
1851 if (num_rids == 0) {
1852 return NT_STATUS_OK;
1855 *names = TALLOC_ARRAY(mem_ctx, char *, num_rids);
1856 *types = TALLOC_ARRAY(mem_ctx, enum lsa_SidType, num_rids);
1858 if ((*names == NULL) || (*types == NULL)) {
1859 result = NT_STATUS_NO_MEMORY;
1860 goto error;
1863 have_mapped = have_unmapped = false;
1865 for (i=0; i<num_rids; i++) {
1866 DOM_SID sid;
1867 struct cache_entry *centry;
1868 fstring tmp;
1870 if (!sid_compose(&sid, domain_sid, rids[i])) {
1871 result = NT_STATUS_INTERNAL_ERROR;
1872 goto error;
1875 centry = wcache_fetch(cache, domain, "SN/%s",
1876 sid_to_fstring(tmp, &sid));
1877 if (!centry) {
1878 goto do_query;
1881 (*types)[i] = SID_NAME_UNKNOWN;
1882 (*names)[i] = talloc_strdup(*names, "");
1884 if (NT_STATUS_IS_OK(centry->status)) {
1885 char *dom;
1886 have_mapped = true;
1887 (*types)[i] = (enum lsa_SidType)centry_uint32(centry);
1889 dom = centry_string(centry, mem_ctx);
1890 if (*domain_name == NULL) {
1891 *domain_name = dom;
1892 } else {
1893 talloc_free(dom);
1896 (*names)[i] = centry_string(centry, *names);
1898 } else if (NT_STATUS_EQUAL(centry->status, NT_STATUS_NONE_MAPPED)) {
1899 have_unmapped = true;
1901 } else {
1902 /* something's definitely wrong */
1903 result = centry->status;
1904 goto error;
1907 centry_free(centry);
1910 if (!have_mapped) {
1911 return NT_STATUS_NONE_MAPPED;
1913 if (!have_unmapped) {
1914 return NT_STATUS_OK;
1916 return STATUS_SOME_UNMAPPED;
1918 do_query:
1920 TALLOC_FREE(*names);
1921 TALLOC_FREE(*types);
1923 result = domain->backend->rids_to_names(domain, mem_ctx, domain_sid,
1924 rids, num_rids, domain_name,
1925 names, types);
1928 None of the queried rids has been found so save all negative entries
1930 if (NT_STATUS_EQUAL(result, NT_STATUS_NONE_MAPPED)) {
1931 for (i = 0; i < num_rids; i++) {
1932 DOM_SID sid;
1933 const char *name = "";
1934 const enum lsa_SidType type = SID_NAME_UNKNOWN;
1935 NTSTATUS status = NT_STATUS_NONE_MAPPED;
1937 if (!sid_compose(&sid, domain_sid, rids[i])) {
1938 return NT_STATUS_INTERNAL_ERROR;
1941 wcache_save_sid_to_name(domain, status, &sid, *domain_name,
1942 name, type);
1945 return result;
1949 Some or all of the queried rids have been found.
1951 if (!NT_STATUS_IS_OK(result) &&
1952 !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED)) {
1953 return result;
1956 refresh_sequence_number(domain, false);
1958 for (i=0; i<num_rids; i++) {
1959 DOM_SID sid;
1960 NTSTATUS status;
1962 if (!sid_compose(&sid, domain_sid, rids[i])) {
1963 result = NT_STATUS_INTERNAL_ERROR;
1964 goto error;
1967 status = (*types)[i] == SID_NAME_UNKNOWN ?
1968 NT_STATUS_NONE_MAPPED : NT_STATUS_OK;
1970 wcache_save_sid_to_name(domain, status, &sid, *domain_name,
1971 (*names)[i], (*types)[i]);
1974 return result;
1976 error:
1977 TALLOC_FREE(*names);
1978 TALLOC_FREE(*types);
1979 return result;
1982 NTSTATUS wcache_query_user(struct winbindd_domain *domain,
1983 TALLOC_CTX *mem_ctx,
1984 const struct dom_sid *user_sid,
1985 struct wbint_userinfo *info)
1987 struct winbind_cache *cache = get_cache(domain);
1988 struct cache_entry *centry = NULL;
1989 NTSTATUS status;
1990 char *sid_string;
1992 if (cache->tdb == NULL) {
1993 return NT_STATUS_NOT_FOUND;
1996 sid_string = sid_string_tos(user_sid);
1997 if (sid_string == NULL) {
1998 return NT_STATUS_NO_MEMORY;
2001 centry = wcache_fetch(cache, domain, "U/%s", sid_string);
2002 TALLOC_FREE(sid_string);
2003 if (centry == NULL) {
2004 return NT_STATUS_NOT_FOUND;
2008 * If we have an access denied cache entry and a cached info3
2009 * in the samlogon cache then do a query. This will force the
2010 * rpc back end to return the info3 data.
2013 if (NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED) &&
2014 netsamlogon_cache_have(user_sid)) {
2015 DEBUG(10, ("query_user: cached access denied and have cached "
2016 "info3\n"));
2017 domain->last_status = NT_STATUS_OK;
2018 centry_free(centry);
2019 return NT_STATUS_NOT_FOUND;
2022 /* if status is not ok then this is a negative hit
2023 and the rest of the data doesn't matter */
2024 status = centry->status;
2025 if (NT_STATUS_IS_OK(status)) {
2026 info->acct_name = centry_string(centry, mem_ctx);
2027 info->full_name = centry_string(centry, mem_ctx);
2028 info->homedir = centry_string(centry, mem_ctx);
2029 info->shell = centry_string(centry, mem_ctx);
2030 info->primary_gid = centry_uint32(centry);
2031 centry_sid(centry, &info->user_sid);
2032 centry_sid(centry, &info->group_sid);
2035 DEBUG(10,("query_user: [Cached] - cached info for domain %s status: "
2036 "%s\n", domain->name, nt_errstr(status) ));
2038 centry_free(centry);
2039 return status;
2042 /* Lookup user information from a rid */
2043 static NTSTATUS query_user(struct winbindd_domain *domain,
2044 TALLOC_CTX *mem_ctx,
2045 const DOM_SID *user_sid,
2046 struct wbint_userinfo *info)
2048 NTSTATUS status;
2050 status = wcache_query_user(domain, mem_ctx, user_sid, info);
2051 if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2052 return status;
2055 ZERO_STRUCTP(info);
2057 /* Return status value returned by seq number check */
2059 if (!NT_STATUS_IS_OK(domain->last_status))
2060 return domain->last_status;
2062 DEBUG(10,("query_user: [Cached] - doing backend query for info for domain %s\n",
2063 domain->name ));
2065 status = domain->backend->query_user(domain, mem_ctx, user_sid, info);
2067 /* and save it */
2068 refresh_sequence_number(domain, false);
2069 wcache_save_user(domain, status, info);
2071 return status;
2074 NTSTATUS wcache_lookup_usergroups(struct winbindd_domain *domain,
2075 TALLOC_CTX *mem_ctx,
2076 const struct dom_sid *user_sid,
2077 uint32_t *pnum_sids,
2078 struct dom_sid **psids)
2080 struct winbind_cache *cache = get_cache(domain);
2081 struct cache_entry *centry = NULL;
2082 NTSTATUS status;
2083 uint32_t i, num_sids;
2084 struct dom_sid *sids;
2085 fstring sid_string;
2087 if (cache->tdb == NULL) {
2088 return NT_STATUS_NOT_FOUND;
2091 centry = wcache_fetch(cache, domain, "UG/%s",
2092 sid_to_fstring(sid_string, user_sid));
2093 if (centry == NULL) {
2094 return NT_STATUS_NOT_FOUND;
2097 /* If we have an access denied cache entry and a cached info3 in the
2098 samlogon cache then do a query. This will force the rpc back end
2099 to return the info3 data. */
2101 if (NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED)
2102 && netsamlogon_cache_have(user_sid)) {
2103 DEBUG(10, ("lookup_usergroups: cached access denied and have "
2104 "cached info3\n"));
2105 domain->last_status = NT_STATUS_OK;
2106 centry_free(centry);
2107 return NT_STATUS_NOT_FOUND;
2110 num_sids = centry_uint32(centry);
2111 sids = talloc_array(mem_ctx, struct dom_sid, num_sids);
2112 if (sids == NULL) {
2113 return NT_STATUS_NO_MEMORY;
2116 for (i=0; i<num_sids; i++) {
2117 centry_sid(centry, &sids[i]);
2120 status = centry->status;
2122 DEBUG(10,("lookup_usergroups: [Cached] - cached info for domain %s "
2123 "status: %s\n", domain->name, nt_errstr(status)));
2125 centry_free(centry);
2127 *pnum_sids = num_sids;
2128 *psids = sids;
2129 return status;
2132 /* Lookup groups a user is a member of. */
2133 static NTSTATUS lookup_usergroups(struct winbindd_domain *domain,
2134 TALLOC_CTX *mem_ctx,
2135 const DOM_SID *user_sid,
2136 uint32 *num_groups, DOM_SID **user_gids)
2138 struct cache_entry *centry = NULL;
2139 NTSTATUS status;
2140 unsigned int i;
2141 fstring sid_string;
2143 status = wcache_lookup_usergroups(domain, mem_ctx, user_sid,
2144 num_groups, user_gids);
2145 if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2146 return status;
2149 (*num_groups) = 0;
2150 (*user_gids) = NULL;
2152 /* Return status value returned by seq number check */
2154 if (!NT_STATUS_IS_OK(domain->last_status))
2155 return domain->last_status;
2157 DEBUG(10,("lookup_usergroups: [Cached] - doing backend query for info for domain %s\n",
2158 domain->name ));
2160 status = domain->backend->lookup_usergroups(domain, mem_ctx, user_sid, num_groups, user_gids);
2162 if ( NT_STATUS_EQUAL(status, NT_STATUS_SYNCHRONIZATION_REQUIRED) )
2163 goto skip_save;
2165 /* and save it */
2166 refresh_sequence_number(domain, false);
2167 centry = centry_start(domain, status);
2168 if (!centry)
2169 goto skip_save;
2171 centry_put_uint32(centry, *num_groups);
2172 for (i=0; i<(*num_groups); i++) {
2173 centry_put_sid(centry, &(*user_gids)[i]);
2176 centry_end(centry, "UG/%s", sid_to_fstring(sid_string, user_sid));
2177 centry_free(centry);
2179 skip_save:
2180 return status;
2183 static char *wcache_make_sidlist(TALLOC_CTX *mem_ctx, uint32_t num_sids,
2184 const struct dom_sid *sids)
2186 uint32_t i;
2187 char *sidlist;
2189 sidlist = talloc_strdup(mem_ctx, "");
2190 if (sidlist == NULL) {
2191 return NULL;
2193 for (i=0; i<num_sids; i++) {
2194 fstring tmp;
2195 sidlist = talloc_asprintf_append_buffer(
2196 sidlist, "/%s", sid_to_fstring(tmp, &sids[i]));
2197 if (sidlist == NULL) {
2198 return NULL;
2201 return sidlist;
2204 NTSTATUS wcache_lookup_useraliases(struct winbindd_domain *domain,
2205 TALLOC_CTX *mem_ctx, uint32_t num_sids,
2206 const struct dom_sid *sids,
2207 uint32_t *pnum_aliases, uint32_t **paliases)
2209 struct winbind_cache *cache = get_cache(domain);
2210 struct cache_entry *centry = NULL;
2211 uint32_t num_aliases;
2212 uint32_t *aliases;
2213 NTSTATUS status;
2214 char *sidlist;
2215 int i;
2217 if (cache->tdb == NULL) {
2218 return NT_STATUS_NOT_FOUND;
2221 if (num_sids == 0) {
2222 *pnum_aliases = 0;
2223 *paliases = NULL;
2224 return NT_STATUS_OK;
2227 /* We need to cache indexed by the whole list of SIDs, the aliases
2228 * resulting might come from any of the SIDs. */
2230 sidlist = wcache_make_sidlist(talloc_tos(), num_sids, sids);
2231 if (sidlist == NULL) {
2232 return NT_STATUS_NO_MEMORY;
2235 centry = wcache_fetch(cache, domain, "UA%s", sidlist);
2236 TALLOC_FREE(sidlist);
2237 if (centry == NULL) {
2238 return NT_STATUS_NOT_FOUND;
2241 num_aliases = centry_uint32(centry);
2242 aliases = talloc_array(mem_ctx, uint32_t, num_aliases);
2243 if (aliases == NULL) {
2244 centry_free(centry);
2245 return NT_STATUS_NO_MEMORY;
2248 for (i=0; i<num_aliases; i++) {
2249 aliases[i] = centry_uint32(centry);
2252 status = centry->status;
2254 DEBUG(10,("lookup_useraliases: [Cached] - cached info for domain: %s "
2255 "status %s\n", domain->name, nt_errstr(status)));
2257 centry_free(centry);
2259 *pnum_aliases = num_aliases;
2260 *paliases = aliases;
2262 return status;
2265 static NTSTATUS lookup_useraliases(struct winbindd_domain *domain,
2266 TALLOC_CTX *mem_ctx,
2267 uint32 num_sids, const DOM_SID *sids,
2268 uint32 *num_aliases, uint32 **alias_rids)
2270 struct cache_entry *centry = NULL;
2271 NTSTATUS status;
2272 char *sidlist;
2273 int i;
2275 status = wcache_lookup_useraliases(domain, mem_ctx, num_sids, sids,
2276 num_aliases, alias_rids);
2277 if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2278 return status;
2281 (*num_aliases) = 0;
2282 (*alias_rids) = NULL;
2284 if (!NT_STATUS_IS_OK(domain->last_status))
2285 return domain->last_status;
2287 DEBUG(10,("lookup_usergroups: [Cached] - doing backend query for info "
2288 "for domain %s\n", domain->name ));
2290 sidlist = wcache_make_sidlist(talloc_tos(), num_sids, sids);
2291 if (sidlist == NULL) {
2292 return NT_STATUS_NO_MEMORY;
2295 status = domain->backend->lookup_useraliases(domain, mem_ctx,
2296 num_sids, sids,
2297 num_aliases, alias_rids);
2299 /* and save it */
2300 refresh_sequence_number(domain, false);
2301 centry = centry_start(domain, status);
2302 if (!centry)
2303 goto skip_save;
2304 centry_put_uint32(centry, *num_aliases);
2305 for (i=0; i<(*num_aliases); i++)
2306 centry_put_uint32(centry, (*alias_rids)[i]);
2307 centry_end(centry, "UA%s", sidlist);
2308 centry_free(centry);
2310 skip_save:
2311 return status;
2314 NTSTATUS wcache_lookup_groupmem(struct winbindd_domain *domain,
2315 TALLOC_CTX *mem_ctx,
2316 const struct dom_sid *group_sid,
2317 uint32_t *num_names,
2318 struct dom_sid **sid_mem, char ***names,
2319 uint32_t **name_types)
2321 struct winbind_cache *cache = get_cache(domain);
2322 struct cache_entry *centry = NULL;
2323 NTSTATUS status;
2324 unsigned int i;
2325 char *sid_string;
2327 if (cache->tdb == NULL) {
2328 return NT_STATUS_NOT_FOUND;
2331 sid_string = sid_string_tos(group_sid);
2332 if (sid_string == NULL) {
2333 return NT_STATUS_NO_MEMORY;
2336 centry = wcache_fetch(cache, domain, "GM/%s", sid_string);
2337 TALLOC_FREE(sid_string);
2338 if (centry == NULL) {
2339 return NT_STATUS_NOT_FOUND;
2342 *sid_mem = NULL;
2343 *names = NULL;
2344 *name_types = NULL;
2346 *num_names = centry_uint32(centry);
2347 if (*num_names == 0) {
2348 centry_free(centry);
2349 return NT_STATUS_OK;
2352 *sid_mem = talloc_array(mem_ctx, DOM_SID, *num_names);
2353 *names = talloc_array(mem_ctx, char *, *num_names);
2354 *name_types = talloc_array(mem_ctx, uint32, *num_names);
2356 if ((*sid_mem == NULL) || (*names == NULL) || (*name_types == NULL)) {
2357 TALLOC_FREE(*sid_mem);
2358 TALLOC_FREE(*names);
2359 TALLOC_FREE(*name_types);
2360 centry_free(centry);
2361 return NT_STATUS_NO_MEMORY;
2364 for (i=0; i<(*num_names); i++) {
2365 centry_sid(centry, &(*sid_mem)[i]);
2366 (*names)[i] = centry_string(centry, mem_ctx);
2367 (*name_types)[i] = centry_uint32(centry);
2370 status = centry->status;
2372 DEBUG(10,("lookup_groupmem: [Cached] - cached info for domain %s "
2373 "status: %s\n", domain->name, nt_errstr(status)));
2375 centry_free(centry);
2376 return status;
2379 static NTSTATUS lookup_groupmem(struct winbindd_domain *domain,
2380 TALLOC_CTX *mem_ctx,
2381 const DOM_SID *group_sid,
2382 enum lsa_SidType type,
2383 uint32 *num_names,
2384 DOM_SID **sid_mem, char ***names,
2385 uint32 **name_types)
2387 struct cache_entry *centry = NULL;
2388 NTSTATUS status;
2389 unsigned int i;
2390 fstring sid_string;
2392 status = wcache_lookup_groupmem(domain, mem_ctx, group_sid, num_names,
2393 sid_mem, names, name_types);
2394 if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2395 return status;
2398 (*num_names) = 0;
2399 (*sid_mem) = NULL;
2400 (*names) = NULL;
2401 (*name_types) = NULL;
2403 /* Return status value returned by seq number check */
2405 if (!NT_STATUS_IS_OK(domain->last_status))
2406 return domain->last_status;
2408 DEBUG(10,("lookup_groupmem: [Cached] - doing backend query for info for domain %s\n",
2409 domain->name ));
2411 status = domain->backend->lookup_groupmem(domain, mem_ctx, group_sid,
2412 type, num_names,
2413 sid_mem, names, name_types);
2415 /* and save it */
2416 refresh_sequence_number(domain, false);
2417 centry = centry_start(domain, status);
2418 if (!centry)
2419 goto skip_save;
2420 centry_put_uint32(centry, *num_names);
2421 for (i=0; i<(*num_names); i++) {
2422 centry_put_sid(centry, &(*sid_mem)[i]);
2423 centry_put_string(centry, (*names)[i]);
2424 centry_put_uint32(centry, (*name_types)[i]);
2426 centry_end(centry, "GM/%s", sid_to_fstring(sid_string, group_sid));
2427 centry_free(centry);
2429 skip_save:
2430 return status;
2433 /* find the sequence number for a domain */
2434 static NTSTATUS sequence_number(struct winbindd_domain *domain, uint32 *seq)
2436 refresh_sequence_number(domain, false);
2438 *seq = domain->sequence_number;
2440 return NT_STATUS_OK;
2443 /* enumerate trusted domains
2444 * (we need to have the list of trustdoms in the cache when we go offline) -
2445 * Guenther */
2446 static NTSTATUS trusted_domains(struct winbindd_domain *domain,
2447 TALLOC_CTX *mem_ctx,
2448 uint32 *num_domains,
2449 char ***names,
2450 char ***alt_names,
2451 DOM_SID **dom_sids)
2453 struct winbind_cache *cache = get_cache(domain);
2454 struct cache_entry *centry = NULL;
2455 NTSTATUS status;
2456 int i;
2458 if (!cache->tdb)
2459 goto do_query;
2461 centry = wcache_fetch(cache, domain, "TRUSTDOMS/%s", domain->name);
2463 if (!centry) {
2464 goto do_query;
2467 *num_domains = centry_uint32(centry);
2469 if (*num_domains) {
2470 (*names) = TALLOC_ARRAY(mem_ctx, char *, *num_domains);
2471 (*alt_names) = TALLOC_ARRAY(mem_ctx, char *, *num_domains);
2472 (*dom_sids) = TALLOC_ARRAY(mem_ctx, DOM_SID, *num_domains);
2474 if (! (*dom_sids) || ! (*names) || ! (*alt_names)) {
2475 smb_panic_fn("trusted_domains out of memory");
2477 } else {
2478 (*names) = NULL;
2479 (*alt_names) = NULL;
2480 (*dom_sids) = NULL;
2483 for (i=0; i<(*num_domains); i++) {
2484 (*names)[i] = centry_string(centry, mem_ctx);
2485 (*alt_names)[i] = centry_string(centry, mem_ctx);
2486 if (!centry_sid(centry, &(*dom_sids)[i])) {
2487 sid_copy(&(*dom_sids)[i], &global_sid_NULL);
2491 status = centry->status;
2493 DEBUG(10,("trusted_domains: [Cached] - cached info for domain %s (%d trusts) status: %s\n",
2494 domain->name, *num_domains, nt_errstr(status) ));
2496 centry_free(centry);
2497 return status;
2499 do_query:
2500 (*num_domains) = 0;
2501 (*dom_sids) = NULL;
2502 (*names) = NULL;
2503 (*alt_names) = NULL;
2505 /* Return status value returned by seq number check */
2507 if (!NT_STATUS_IS_OK(domain->last_status))
2508 return domain->last_status;
2510 DEBUG(10,("trusted_domains: [Cached] - doing backend query for info for domain %s\n",
2511 domain->name ));
2513 status = domain->backend->trusted_domains(domain, mem_ctx, num_domains,
2514 names, alt_names, dom_sids);
2516 /* no trusts gives NT_STATUS_NO_MORE_ENTRIES resetting to NT_STATUS_OK
2517 * so that the generic centry handling still applies correctly -
2518 * Guenther*/
2520 if (!NT_STATUS_IS_ERR(status)) {
2521 status = NT_STATUS_OK;
2525 #if 0 /* Disabled as we want the trust dom list to be managed by
2526 the main parent and always to make the query. --jerry */
2528 /* and save it */
2529 refresh_sequence_number(domain, false);
2531 centry = centry_start(domain, status);
2532 if (!centry)
2533 goto skip_save;
2535 centry_put_uint32(centry, *num_domains);
2537 for (i=0; i<(*num_domains); i++) {
2538 centry_put_string(centry, (*names)[i]);
2539 centry_put_string(centry, (*alt_names)[i]);
2540 centry_put_sid(centry, &(*dom_sids)[i]);
2543 centry_end(centry, "TRUSTDOMS/%s", domain->name);
2545 centry_free(centry);
2547 skip_save:
2548 #endif
2550 return status;
2553 /* get lockout policy */
2554 static NTSTATUS lockout_policy(struct winbindd_domain *domain,
2555 TALLOC_CTX *mem_ctx,
2556 struct samr_DomInfo12 *policy)
2558 struct winbind_cache *cache = get_cache(domain);
2559 struct cache_entry *centry = NULL;
2560 NTSTATUS status;
2562 if (!cache->tdb)
2563 goto do_query;
2565 centry = wcache_fetch(cache, domain, "LOC_POL/%s", domain->name);
2567 if (!centry)
2568 goto do_query;
2570 policy->lockout_duration = centry_nttime(centry);
2571 policy->lockout_window = centry_nttime(centry);
2572 policy->lockout_threshold = centry_uint16(centry);
2574 status = centry->status;
2576 DEBUG(10,("lockout_policy: [Cached] - cached info for domain %s status: %s\n",
2577 domain->name, nt_errstr(status) ));
2579 centry_free(centry);
2580 return status;
2582 do_query:
2583 ZERO_STRUCTP(policy);
2585 /* Return status value returned by seq number check */
2587 if (!NT_STATUS_IS_OK(domain->last_status))
2588 return domain->last_status;
2590 DEBUG(10,("lockout_policy: [Cached] - doing backend query for info for domain %s\n",
2591 domain->name ));
2593 status = domain->backend->lockout_policy(domain, mem_ctx, policy);
2595 /* and save it */
2596 refresh_sequence_number(domain, false);
2597 wcache_save_lockout_policy(domain, status, policy);
2599 return status;
2602 /* get password policy */
2603 static NTSTATUS password_policy(struct winbindd_domain *domain,
2604 TALLOC_CTX *mem_ctx,
2605 struct samr_DomInfo1 *policy)
2607 struct winbind_cache *cache = get_cache(domain);
2608 struct cache_entry *centry = NULL;
2609 NTSTATUS status;
2611 if (!cache->tdb)
2612 goto do_query;
2614 centry = wcache_fetch(cache, domain, "PWD_POL/%s", domain->name);
2616 if (!centry)
2617 goto do_query;
2619 policy->min_password_length = centry_uint16(centry);
2620 policy->password_history_length = centry_uint16(centry);
2621 policy->password_properties = centry_uint32(centry);
2622 policy->max_password_age = centry_nttime(centry);
2623 policy->min_password_age = centry_nttime(centry);
2625 status = centry->status;
2627 DEBUG(10,("lockout_policy: [Cached] - cached info for domain %s status: %s\n",
2628 domain->name, nt_errstr(status) ));
2630 centry_free(centry);
2631 return status;
2633 do_query:
2634 ZERO_STRUCTP(policy);
2636 /* Return status value returned by seq number check */
2638 if (!NT_STATUS_IS_OK(domain->last_status))
2639 return domain->last_status;
2641 DEBUG(10,("password_policy: [Cached] - doing backend query for info for domain %s\n",
2642 domain->name ));
2644 status = domain->backend->password_policy(domain, mem_ctx, policy);
2646 /* and save it */
2647 refresh_sequence_number(domain, false);
2648 if (NT_STATUS_IS_OK(status)) {
2649 wcache_save_password_policy(domain, status, policy);
2652 return status;
2656 /* Invalidate cached user and group lists coherently */
2658 static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf,
2659 void *state)
2661 if (strncmp((const char *)kbuf.dptr, "UL/", 3) == 0 ||
2662 strncmp((const char *)kbuf.dptr, "GL/", 3) == 0)
2663 tdb_delete(the_tdb, kbuf);
2665 return 0;
2668 /* Invalidate the getpwnam and getgroups entries for a winbindd domain */
2670 void wcache_invalidate_samlogon(struct winbindd_domain *domain,
2671 struct netr_SamInfo3 *info3)
2673 DOM_SID sid;
2674 fstring key_str, sid_string;
2675 struct winbind_cache *cache;
2677 /* dont clear cached U/SID and UG/SID entries when we want to logon
2678 * offline - gd */
2680 if (lp_winbind_offline_logon()) {
2681 return;
2684 if (!domain)
2685 return;
2687 cache = get_cache(domain);
2689 if (!cache->tdb) {
2690 return;
2693 sid_copy(&sid, info3->base.domain_sid);
2694 sid_append_rid(&sid, info3->base.rid);
2696 /* Clear U/SID cache entry */
2697 fstr_sprintf(key_str, "U/%s", sid_to_fstring(sid_string, &sid));
2698 DEBUG(10, ("wcache_invalidate_samlogon: clearing %s\n", key_str));
2699 tdb_delete(cache->tdb, string_tdb_data(key_str));
2701 /* Clear UG/SID cache entry */
2702 fstr_sprintf(key_str, "UG/%s", sid_to_fstring(sid_string, &sid));
2703 DEBUG(10, ("wcache_invalidate_samlogon: clearing %s\n", key_str));
2704 tdb_delete(cache->tdb, string_tdb_data(key_str));
2706 /* Samba/winbindd never needs this. */
2707 netsamlogon_clear_cached_user(info3);
2710 bool wcache_invalidate_cache(void)
2712 struct winbindd_domain *domain;
2714 for (domain = domain_list(); domain; domain = domain->next) {
2715 struct winbind_cache *cache = get_cache(domain);
2717 DEBUG(10, ("wcache_invalidate_cache: invalidating cache "
2718 "entries for %s\n", domain->name));
2719 if (cache) {
2720 if (cache->tdb) {
2721 tdb_traverse(cache->tdb, traverse_fn, NULL);
2722 } else {
2723 return false;
2727 return true;
2730 bool init_wcache(void)
2732 if (wcache == NULL) {
2733 wcache = SMB_XMALLOC_P(struct winbind_cache);
2734 ZERO_STRUCTP(wcache);
2737 if (wcache->tdb != NULL)
2738 return true;
2740 /* when working offline we must not clear the cache on restart */
2741 wcache->tdb = tdb_open_log(cache_path("winbindd_cache.tdb"),
2742 WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE,
2743 lp_winbind_offline_logon() ? TDB_DEFAULT : (TDB_DEFAULT | TDB_CLEAR_IF_FIRST),
2744 O_RDWR|O_CREAT, 0600);
2746 if (wcache->tdb == NULL) {
2747 DEBUG(0,("Failed to open winbindd_cache.tdb!\n"));
2748 return false;
2751 return true;
2754 /************************************************************************
2755 This is called by the parent to initialize the cache file.
2756 We don't need sophisticated locking here as we know we're the
2757 only opener.
2758 ************************************************************************/
2760 bool initialize_winbindd_cache(void)
2762 bool cache_bad = true;
2763 uint32 vers;
2765 if (!init_wcache()) {
2766 DEBUG(0,("initialize_winbindd_cache: init_wcache failed.\n"));
2767 return false;
2770 /* Check version number. */
2771 if (tdb_fetch_uint32(wcache->tdb, WINBINDD_CACHE_VERSION_KEYSTR, &vers) &&
2772 vers == WINBINDD_CACHE_VERSION) {
2773 cache_bad = false;
2776 if (cache_bad) {
2777 DEBUG(0,("initialize_winbindd_cache: clearing cache "
2778 "and re-creating with version number %d\n",
2779 WINBINDD_CACHE_VERSION ));
2781 tdb_close(wcache->tdb);
2782 wcache->tdb = NULL;
2784 if (unlink(cache_path("winbindd_cache.tdb")) == -1) {
2785 DEBUG(0,("initialize_winbindd_cache: unlink %s failed %s ",
2786 cache_path("winbindd_cache.tdb"),
2787 strerror(errno) ));
2788 return false;
2790 if (!init_wcache()) {
2791 DEBUG(0,("initialize_winbindd_cache: re-initialization "
2792 "init_wcache failed.\n"));
2793 return false;
2796 /* Write the version. */
2797 if (!tdb_store_uint32(wcache->tdb, WINBINDD_CACHE_VERSION_KEYSTR, WINBINDD_CACHE_VERSION)) {
2798 DEBUG(0,("initialize_winbindd_cache: version number store failed %s\n",
2799 tdb_errorstr(wcache->tdb) ));
2800 return false;
2804 tdb_close(wcache->tdb);
2805 wcache->tdb = NULL;
2806 return true;
2809 void close_winbindd_cache(void)
2811 if (!wcache) {
2812 return;
2814 if (wcache->tdb) {
2815 tdb_close(wcache->tdb);
2816 wcache->tdb = NULL;
2820 bool lookup_cached_sid(TALLOC_CTX *mem_ctx, const DOM_SID *sid,
2821 char **domain_name, char **name,
2822 enum lsa_SidType *type)
2824 struct winbindd_domain *domain;
2825 NTSTATUS status;
2827 domain = find_lookup_domain_from_sid(sid);
2828 if (domain == NULL) {
2829 return false;
2831 status = wcache_sid_to_name(domain, sid, mem_ctx, domain_name, name,
2832 type);
2833 return NT_STATUS_IS_OK(status);
2836 bool lookup_cached_name(TALLOC_CTX *mem_ctx,
2837 const char *domain_name,
2838 const char *name,
2839 DOM_SID *sid,
2840 enum lsa_SidType *type)
2842 struct winbindd_domain *domain;
2843 NTSTATUS status;
2844 bool original_online_state;
2846 domain = find_lookup_domain_from_name(domain_name);
2847 if (domain == NULL) {
2848 return false;
2851 /* If we are doing a cached logon, temporarily set the domain
2852 offline so the cache won't expire the entry */
2854 original_online_state = domain->online;
2855 domain->online = false;
2856 status = wcache_name_to_sid(domain, domain_name, name, sid, type);
2857 domain->online = original_online_state;
2859 return NT_STATUS_IS_OK(status);
2862 void cache_name2sid(struct winbindd_domain *domain,
2863 const char *domain_name, const char *name,
2864 enum lsa_SidType type, const DOM_SID *sid)
2866 refresh_sequence_number(domain, false);
2867 wcache_save_name_to_sid(domain, NT_STATUS_OK, domain_name, name,
2868 sid, type);
2872 * The original idea that this cache only contains centries has
2873 * been blurred - now other stuff gets put in here. Ensure we
2874 * ignore these things on cleanup.
2877 static int traverse_fn_cleanup(TDB_CONTEXT *the_tdb, TDB_DATA kbuf,
2878 TDB_DATA dbuf, void *state)
2880 struct cache_entry *centry;
2882 if (is_non_centry_key(kbuf)) {
2883 return 0;
2886 centry = wcache_fetch_raw((char *)kbuf.dptr);
2887 if (!centry) {
2888 return 0;
2891 if (!NT_STATUS_IS_OK(centry->status)) {
2892 DEBUG(10,("deleting centry %s\n", (const char *)kbuf.dptr));
2893 tdb_delete(the_tdb, kbuf);
2896 centry_free(centry);
2897 return 0;
2900 /* flush the cache */
2901 void wcache_flush_cache(void)
2903 if (!wcache)
2904 return;
2905 if (wcache->tdb) {
2906 tdb_close(wcache->tdb);
2907 wcache->tdb = NULL;
2909 if (!winbindd_use_cache()) {
2910 return;
2913 /* when working offline we must not clear the cache on restart */
2914 wcache->tdb = tdb_open_log(cache_path("winbindd_cache.tdb"),
2915 WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE,
2916 lp_winbind_offline_logon() ? TDB_DEFAULT : (TDB_DEFAULT | TDB_CLEAR_IF_FIRST),
2917 O_RDWR|O_CREAT, 0600);
2919 if (!wcache->tdb) {
2920 DEBUG(0,("Failed to open winbindd_cache.tdb!\n"));
2921 return;
2924 tdb_traverse(wcache->tdb, traverse_fn_cleanup, NULL);
2926 DEBUG(10,("wcache_flush_cache success\n"));
2929 /* Count cached creds */
2931 static int traverse_fn_cached_creds(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf,
2932 void *state)
2934 int *cred_count = (int*)state;
2936 if (strncmp((const char *)kbuf.dptr, "CRED/", 5) == 0) {
2937 (*cred_count)++;
2939 return 0;
2942 NTSTATUS wcache_count_cached_creds(struct winbindd_domain *domain, int *count)
2944 struct winbind_cache *cache = get_cache(domain);
2946 *count = 0;
2948 if (!cache->tdb) {
2949 return NT_STATUS_INTERNAL_DB_ERROR;
2952 tdb_traverse(cache->tdb, traverse_fn_cached_creds, (void *)count);
2954 return NT_STATUS_OK;
2957 struct cred_list {
2958 struct cred_list *prev, *next;
2959 TDB_DATA key;
2960 fstring name;
2961 time_t created;
2963 static struct cred_list *wcache_cred_list;
2965 static int traverse_fn_get_credlist(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf,
2966 void *state)
2968 struct cred_list *cred;
2970 if (strncmp((const char *)kbuf.dptr, "CRED/", 5) == 0) {
2972 cred = SMB_MALLOC_P(struct cred_list);
2973 if (cred == NULL) {
2974 DEBUG(0,("traverse_fn_remove_first_creds: failed to malloc new entry for list\n"));
2975 return -1;
2978 ZERO_STRUCTP(cred);
2980 /* save a copy of the key */
2982 fstrcpy(cred->name, (const char *)kbuf.dptr);
2983 DLIST_ADD(wcache_cred_list, cred);
2986 return 0;
2989 NTSTATUS wcache_remove_oldest_cached_creds(struct winbindd_domain *domain, const DOM_SID *sid)
2991 struct winbind_cache *cache = get_cache(domain);
2992 NTSTATUS status;
2993 int ret;
2994 struct cred_list *cred, *oldest = NULL;
2996 if (!cache->tdb) {
2997 return NT_STATUS_INTERNAL_DB_ERROR;
3000 /* we possibly already have an entry */
3001 if (sid && NT_STATUS_IS_OK(wcache_cached_creds_exist(domain, sid))) {
3003 fstring key_str, tmp;
3005 DEBUG(11,("we already have an entry, deleting that\n"));
3007 fstr_sprintf(key_str, "CRED/%s", sid_to_fstring(tmp, sid));
3009 tdb_delete(cache->tdb, string_tdb_data(key_str));
3011 return NT_STATUS_OK;
3014 ret = tdb_traverse(cache->tdb, traverse_fn_get_credlist, NULL);
3015 if (ret == 0) {
3016 return NT_STATUS_OK;
3017 } else if ((ret == -1) || (wcache_cred_list == NULL)) {
3018 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3021 ZERO_STRUCTP(oldest);
3023 for (cred = wcache_cred_list; cred; cred = cred->next) {
3025 TDB_DATA data;
3026 time_t t;
3028 data = tdb_fetch(cache->tdb, string_tdb_data(cred->name));
3029 if (!data.dptr) {
3030 DEBUG(10,("wcache_remove_oldest_cached_creds: entry for [%s] not found\n",
3031 cred->name));
3032 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
3033 goto done;
3036 t = IVAL(data.dptr, 0);
3037 SAFE_FREE(data.dptr);
3039 if (!oldest) {
3040 oldest = SMB_MALLOC_P(struct cred_list);
3041 if (oldest == NULL) {
3042 status = NT_STATUS_NO_MEMORY;
3043 goto done;
3046 fstrcpy(oldest->name, cred->name);
3047 oldest->created = t;
3048 continue;
3051 if (t < oldest->created) {
3052 fstrcpy(oldest->name, cred->name);
3053 oldest->created = t;
3057 if (tdb_delete(cache->tdb, string_tdb_data(oldest->name)) == 0) {
3058 status = NT_STATUS_OK;
3059 } else {
3060 status = NT_STATUS_UNSUCCESSFUL;
3062 done:
3063 SAFE_FREE(wcache_cred_list);
3064 SAFE_FREE(oldest);
3066 return status;
3069 /* Change the global online/offline state. */
3070 bool set_global_winbindd_state_offline(void)
3072 TDB_DATA data;
3074 DEBUG(10,("set_global_winbindd_state_offline: offline requested.\n"));
3076 /* Only go offline if someone has created
3077 the key "WINBINDD_OFFLINE" in the cache tdb. */
3079 if (wcache == NULL || wcache->tdb == NULL) {
3080 DEBUG(10,("set_global_winbindd_state_offline: wcache not open yet.\n"));
3081 return false;
3084 if (!lp_winbind_offline_logon()) {
3085 DEBUG(10,("set_global_winbindd_state_offline: rejecting.\n"));
3086 return false;
3089 if (global_winbindd_offline_state) {
3090 /* Already offline. */
3091 return true;
3094 data = tdb_fetch_bystring( wcache->tdb, "WINBINDD_OFFLINE" );
3096 if (!data.dptr || data.dsize != 4) {
3097 DEBUG(10,("set_global_winbindd_state_offline: offline state not set.\n"));
3098 SAFE_FREE(data.dptr);
3099 return false;
3100 } else {
3101 DEBUG(10,("set_global_winbindd_state_offline: offline state set.\n"));
3102 global_winbindd_offline_state = true;
3103 SAFE_FREE(data.dptr);
3104 return true;
3108 void set_global_winbindd_state_online(void)
3110 DEBUG(10,("set_global_winbindd_state_online: online requested.\n"));
3112 if (!lp_winbind_offline_logon()) {
3113 DEBUG(10,("set_global_winbindd_state_online: rejecting.\n"));
3114 return;
3117 if (!global_winbindd_offline_state) {
3118 /* Already online. */
3119 return;
3121 global_winbindd_offline_state = false;
3123 if (!wcache->tdb) {
3124 return;
3127 /* Ensure there is no key "WINBINDD_OFFLINE" in the cache tdb. */
3128 tdb_delete_bystring(wcache->tdb, "WINBINDD_OFFLINE");
3131 bool get_global_winbindd_state_offline(void)
3133 return global_winbindd_offline_state;
3136 /***********************************************************************
3137 Validate functions for all possible cache tdb keys.
3138 ***********************************************************************/
3140 static struct cache_entry *create_centry_validate(const char *kstr, TDB_DATA data,
3141 struct tdb_validation_status *state)
3143 struct cache_entry *centry;
3145 centry = SMB_XMALLOC_P(struct cache_entry);
3146 centry->data = (unsigned char *)memdup(data.dptr, data.dsize);
3147 if (!centry->data) {
3148 SAFE_FREE(centry);
3149 return NULL;
3151 centry->len = data.dsize;
3152 centry->ofs = 0;
3154 if (centry->len < 8) {
3155 /* huh? corrupt cache? */
3156 DEBUG(0,("create_centry_validate: Corrupt cache for key %s (len < 8) ?\n", kstr));
3157 centry_free(centry);
3158 state->bad_entry = true;
3159 state->success = false;
3160 return NULL;
3163 centry->status = NT_STATUS(centry_uint32(centry));
3164 centry->sequence_number = centry_uint32(centry);
3165 return centry;
3168 static int validate_seqnum(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3169 struct tdb_validation_status *state)
3171 if (dbuf.dsize != 8) {
3172 DEBUG(0,("validate_seqnum: Corrupt cache for key %s (len %u != 8) ?\n",
3173 keystr, (unsigned int)dbuf.dsize ));
3174 state->bad_entry = true;
3175 return 1;
3177 return 0;
3180 static int validate_ns(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3181 struct tdb_validation_status *state)
3183 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3184 if (!centry) {
3185 return 1;
3188 (void)centry_uint32(centry);
3189 if (NT_STATUS_IS_OK(centry->status)) {
3190 DOM_SID sid;
3191 (void)centry_sid(centry, &sid);
3194 centry_free(centry);
3196 if (!(state->success)) {
3197 return 1;
3199 DEBUG(10,("validate_ns: %s ok\n", keystr));
3200 return 0;
3203 static int validate_sn(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3204 struct tdb_validation_status *state)
3206 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3207 if (!centry) {
3208 return 1;
3211 if (NT_STATUS_IS_OK(centry->status)) {
3212 (void)centry_uint32(centry);
3213 (void)centry_string(centry, mem_ctx);
3214 (void)centry_string(centry, mem_ctx);
3217 centry_free(centry);
3219 if (!(state->success)) {
3220 return 1;
3222 DEBUG(10,("validate_sn: %s ok\n", keystr));
3223 return 0;
3226 static int validate_u(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3227 struct tdb_validation_status *state)
3229 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3230 DOM_SID sid;
3232 if (!centry) {
3233 return 1;
3236 (void)centry_string(centry, mem_ctx);
3237 (void)centry_string(centry, mem_ctx);
3238 (void)centry_string(centry, mem_ctx);
3239 (void)centry_string(centry, mem_ctx);
3240 (void)centry_uint32(centry);
3241 (void)centry_sid(centry, &sid);
3242 (void)centry_sid(centry, &sid);
3244 centry_free(centry);
3246 if (!(state->success)) {
3247 return 1;
3249 DEBUG(10,("validate_u: %s ok\n", keystr));
3250 return 0;
3253 static int validate_loc_pol(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3254 struct tdb_validation_status *state)
3256 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3258 if (!centry) {
3259 return 1;
3262 (void)centry_nttime(centry);
3263 (void)centry_nttime(centry);
3264 (void)centry_uint16(centry);
3266 centry_free(centry);
3268 if (!(state->success)) {
3269 return 1;
3271 DEBUG(10,("validate_loc_pol: %s ok\n", keystr));
3272 return 0;
3275 static int validate_pwd_pol(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3276 struct tdb_validation_status *state)
3278 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3280 if (!centry) {
3281 return 1;
3284 (void)centry_uint16(centry);
3285 (void)centry_uint16(centry);
3286 (void)centry_uint32(centry);
3287 (void)centry_nttime(centry);
3288 (void)centry_nttime(centry);
3290 centry_free(centry);
3292 if (!(state->success)) {
3293 return 1;
3295 DEBUG(10,("validate_pwd_pol: %s ok\n", keystr));
3296 return 0;
3299 static int validate_cred(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3300 struct tdb_validation_status *state)
3302 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3304 if (!centry) {
3305 return 1;
3308 (void)centry_time(centry);
3309 (void)centry_hash16(centry, mem_ctx);
3311 /* We only have 17 bytes more data in the salted cred case. */
3312 if (centry->len - centry->ofs == 17) {
3313 (void)centry_hash16(centry, mem_ctx);
3316 centry_free(centry);
3318 if (!(state->success)) {
3319 return 1;
3321 DEBUG(10,("validate_cred: %s ok\n", keystr));
3322 return 0;
3325 static int validate_ul(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3326 struct tdb_validation_status *state)
3328 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3329 int32 num_entries, i;
3331 if (!centry) {
3332 return 1;
3335 num_entries = (int32)centry_uint32(centry);
3337 for (i=0; i< num_entries; i++) {
3338 DOM_SID sid;
3339 (void)centry_string(centry, mem_ctx);
3340 (void)centry_string(centry, mem_ctx);
3341 (void)centry_string(centry, mem_ctx);
3342 (void)centry_string(centry, mem_ctx);
3343 (void)centry_sid(centry, &sid);
3344 (void)centry_sid(centry, &sid);
3347 centry_free(centry);
3349 if (!(state->success)) {
3350 return 1;
3352 DEBUG(10,("validate_ul: %s ok\n", keystr));
3353 return 0;
3356 static int validate_gl(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3357 struct tdb_validation_status *state)
3359 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3360 int32 num_entries, i;
3362 if (!centry) {
3363 return 1;
3366 num_entries = centry_uint32(centry);
3368 for (i=0; i< num_entries; i++) {
3369 (void)centry_string(centry, mem_ctx);
3370 (void)centry_string(centry, mem_ctx);
3371 (void)centry_uint32(centry);
3374 centry_free(centry);
3376 if (!(state->success)) {
3377 return 1;
3379 DEBUG(10,("validate_gl: %s ok\n", keystr));
3380 return 0;
3383 static int validate_ug(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3384 struct tdb_validation_status *state)
3386 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3387 int32 num_groups, i;
3389 if (!centry) {
3390 return 1;
3393 num_groups = centry_uint32(centry);
3395 for (i=0; i< num_groups; i++) {
3396 DOM_SID sid;
3397 centry_sid(centry, &sid);
3400 centry_free(centry);
3402 if (!(state->success)) {
3403 return 1;
3405 DEBUG(10,("validate_ug: %s ok\n", keystr));
3406 return 0;
3409 static int validate_ua(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3410 struct tdb_validation_status *state)
3412 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3413 int32 num_aliases, i;
3415 if (!centry) {
3416 return 1;
3419 num_aliases = centry_uint32(centry);
3421 for (i=0; i < num_aliases; i++) {
3422 (void)centry_uint32(centry);
3425 centry_free(centry);
3427 if (!(state->success)) {
3428 return 1;
3430 DEBUG(10,("validate_ua: %s ok\n", keystr));
3431 return 0;
3434 static int validate_gm(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3435 struct tdb_validation_status *state)
3437 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3438 int32 num_names, i;
3440 if (!centry) {
3441 return 1;
3444 num_names = centry_uint32(centry);
3446 for (i=0; i< num_names; i++) {
3447 DOM_SID sid;
3448 centry_sid(centry, &sid);
3449 (void)centry_string(centry, mem_ctx);
3450 (void)centry_uint32(centry);
3453 centry_free(centry);
3455 if (!(state->success)) {
3456 return 1;
3458 DEBUG(10,("validate_gm: %s ok\n", keystr));
3459 return 0;
3462 static int validate_dr(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3463 struct tdb_validation_status *state)
3465 /* Can't say anything about this other than must be nonzero. */
3466 if (dbuf.dsize == 0) {
3467 DEBUG(0,("validate_dr: Corrupt cache for key %s (len == 0) ?\n",
3468 keystr));
3469 state->bad_entry = true;
3470 state->success = false;
3471 return 1;
3474 DEBUG(10,("validate_dr: %s ok\n", keystr));
3475 return 0;
3478 static int validate_de(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3479 struct tdb_validation_status *state)
3481 /* Can't say anything about this other than must be nonzero. */
3482 if (dbuf.dsize == 0) {
3483 DEBUG(0,("validate_de: Corrupt cache for key %s (len == 0) ?\n",
3484 keystr));
3485 state->bad_entry = true;
3486 state->success = false;
3487 return 1;
3490 DEBUG(10,("validate_de: %s ok\n", keystr));
3491 return 0;
3494 static int validate_pwinfo(TALLOC_CTX *mem_ctx, const char *keystr,
3495 TDB_DATA dbuf, struct tdb_validation_status *state)
3497 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3499 if (!centry) {
3500 return 1;
3503 (void)centry_string(centry, mem_ctx);
3504 (void)centry_string(centry, mem_ctx);
3505 (void)centry_string(centry, mem_ctx);
3506 (void)centry_uint32(centry);
3508 centry_free(centry);
3510 if (!(state->success)) {
3511 return 1;
3513 DEBUG(10,("validate_pwinfo: %s ok\n", keystr));
3514 return 0;
3517 static int validate_nss_an(TALLOC_CTX *mem_ctx, const char *keystr,
3518 TDB_DATA dbuf,
3519 struct tdb_validation_status *state)
3521 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3523 if (!centry) {
3524 return 1;
3527 (void)centry_string( centry, mem_ctx );
3529 centry_free(centry);
3531 if (!(state->success)) {
3532 return 1;
3534 DEBUG(10,("validate_pwinfo: %s ok\n", keystr));
3535 return 0;
3538 static int validate_nss_na(TALLOC_CTX *mem_ctx, const char *keystr,
3539 TDB_DATA dbuf,
3540 struct tdb_validation_status *state)
3542 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3544 if (!centry) {
3545 return 1;
3548 (void)centry_string( centry, mem_ctx );
3550 centry_free(centry);
3552 if (!(state->success)) {
3553 return 1;
3555 DEBUG(10,("validate_pwinfo: %s ok\n", keystr));
3556 return 0;
3559 static int validate_trustdoms(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3560 struct tdb_validation_status *state)
3562 struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
3563 int32 num_domains, i;
3565 if (!centry) {
3566 return 1;
3569 num_domains = centry_uint32(centry);
3571 for (i=0; i< num_domains; i++) {
3572 DOM_SID sid;
3573 (void)centry_string(centry, mem_ctx);
3574 (void)centry_string(centry, mem_ctx);
3575 (void)centry_sid(centry, &sid);
3578 centry_free(centry);
3580 if (!(state->success)) {
3581 return 1;
3583 DEBUG(10,("validate_trustdoms: %s ok\n", keystr));
3584 return 0;
3587 static int validate_trustdomcache(TALLOC_CTX *mem_ctx, const char *keystr,
3588 TDB_DATA dbuf,
3589 struct tdb_validation_status *state)
3591 if (dbuf.dsize == 0) {
3592 DEBUG(0, ("validate_trustdomcache: Corrupt cache for "
3593 "key %s (len ==0) ?\n", keystr));
3594 state->bad_entry = true;
3595 state->success = false;
3596 return 1;
3599 DEBUG(10, ("validate_trustdomcache: %s ok\n", keystr));
3600 DEBUGADD(10, (" Don't trust me, I am a DUMMY!\n"));
3601 return 0;
3604 static int validate_offline(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3605 struct tdb_validation_status *state)
3607 if (dbuf.dsize != 4) {
3608 DEBUG(0,("validate_offline: Corrupt cache for key %s (len %u != 4) ?\n",
3609 keystr, (unsigned int)dbuf.dsize ));
3610 state->bad_entry = true;
3611 state->success = false;
3612 return 1;
3614 DEBUG(10,("validate_offline: %s ok\n", keystr));
3615 return 0;
3618 static int validate_ndr(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3619 struct tdb_validation_status *state)
3622 * Ignore validation for now. The proper way to do this is with a
3623 * checksum. Just pure parsing does not really catch much.
3625 return 0;
3628 static int validate_cache_version(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
3629 struct tdb_validation_status *state)
3631 if (dbuf.dsize != 4) {
3632 DEBUG(0, ("validate_cache_version: Corrupt cache for "
3633 "key %s (len %u != 4) ?\n",
3634 keystr, (unsigned int)dbuf.dsize));
3635 state->bad_entry = true;
3636 state->success = false;
3637 return 1;
3640 DEBUG(10, ("validate_cache_version: %s ok\n", keystr));
3641 return 0;
3644 /***********************************************************************
3645 A list of all possible cache tdb keys with associated validation
3646 functions.
3647 ***********************************************************************/
3649 struct key_val_struct {
3650 const char *keyname;
3651 int (*validate_data_fn)(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf, struct tdb_validation_status* state);
3652 } key_val[] = {
3653 {"SEQNUM/", validate_seqnum},
3654 {"NS/", validate_ns},
3655 {"SN/", validate_sn},
3656 {"U/", validate_u},
3657 {"LOC_POL/", validate_loc_pol},
3658 {"PWD_POL/", validate_pwd_pol},
3659 {"CRED/", validate_cred},
3660 {"UL/", validate_ul},
3661 {"GL/", validate_gl},
3662 {"UG/", validate_ug},
3663 {"UA", validate_ua},
3664 {"GM/", validate_gm},
3665 {"DR/", validate_dr},
3666 {"DE/", validate_de},
3667 {"NSS/PWINFO/", validate_pwinfo},
3668 {"TRUSTDOMS/", validate_trustdoms},
3669 {"TRUSTDOMCACHE/", validate_trustdomcache},
3670 {"NSS/NA/", validate_nss_na},
3671 {"NSS/AN/", validate_nss_an},
3672 {"WINBINDD_OFFLINE", validate_offline},
3673 {"NDR/", validate_ndr},
3674 {WINBINDD_CACHE_VERSION_KEYSTR, validate_cache_version},
3675 {NULL, NULL}
3678 /***********************************************************************
3679 Function to look at every entry in the tdb and validate it as far as
3680 possible.
3681 ***********************************************************************/
3683 static int cache_traverse_validate_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, void *state)
3685 int i;
3686 unsigned int max_key_len = 1024;
3687 struct tdb_validation_status *v_state = (struct tdb_validation_status *)state;
3689 /* Paranoia check. */
3690 if (strncmp("UA/", (const char *)kbuf.dptr, 3) == 0) {
3691 max_key_len = 1024 * 1024;
3693 if (kbuf.dsize > max_key_len) {
3694 DEBUG(0, ("cache_traverse_validate_fn: key length too large: "
3695 "(%u) > (%u)\n\n",
3696 (unsigned int)kbuf.dsize, (unsigned int)max_key_len));
3697 return 1;
3700 for (i = 0; key_val[i].keyname; i++) {
3701 size_t namelen = strlen(key_val[i].keyname);
3702 if (kbuf.dsize >= namelen && (
3703 strncmp(key_val[i].keyname, (const char *)kbuf.dptr, namelen)) == 0) {
3704 TALLOC_CTX *mem_ctx;
3705 char *keystr;
3706 int ret;
3708 keystr = SMB_MALLOC_ARRAY(char, kbuf.dsize+1);
3709 if (!keystr) {
3710 return 1;
3712 memcpy(keystr, kbuf.dptr, kbuf.dsize);
3713 keystr[kbuf.dsize] = '\0';
3715 mem_ctx = talloc_init("validate_ctx");
3716 if (!mem_ctx) {
3717 SAFE_FREE(keystr);
3718 return 1;
3721 ret = key_val[i].validate_data_fn(mem_ctx, keystr, dbuf,
3722 v_state);
3724 SAFE_FREE(keystr);
3725 talloc_destroy(mem_ctx);
3726 return ret;
3730 DEBUG(0,("cache_traverse_validate_fn: unknown cache entry\nkey :\n"));
3731 dump_data(0, (uint8 *)kbuf.dptr, kbuf.dsize);
3732 DEBUG(0,("data :\n"));
3733 dump_data(0, (uint8 *)dbuf.dptr, dbuf.dsize);
3734 v_state->unknown_key = true;
3735 v_state->success = false;
3736 return 1; /* terminate. */
3739 static void validate_panic(const char *const why)
3741 DEBUG(0,("validating cache: would panic %s\n", why ));
3742 DEBUGADD(0, ("exiting instead (cache validation mode)\n"));
3743 exit(47);
3746 /***********************************************************************
3747 Try and validate every entry in the winbindd cache. If we fail here,
3748 delete the cache tdb and return non-zero.
3749 ***********************************************************************/
3751 int winbindd_validate_cache(void)
3753 int ret = -1;
3754 const char *tdb_path = cache_path("winbindd_cache.tdb");
3755 TDB_CONTEXT *tdb = NULL;
3757 DEBUG(10, ("winbindd_validate_cache: replacing panic function\n"));
3758 smb_panic_fn = validate_panic;
3761 tdb = tdb_open_log(tdb_path,
3762 WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE,
3763 ( lp_winbind_offline_logon()
3764 ? TDB_DEFAULT
3765 : TDB_DEFAULT | TDB_CLEAR_IF_FIRST ),
3766 O_RDWR|O_CREAT,
3767 0600);
3768 if (!tdb) {
3769 DEBUG(0, ("winbindd_validate_cache: "
3770 "error opening/initializing tdb\n"));
3771 goto done;
3773 tdb_close(tdb);
3775 ret = tdb_validate_and_backup(tdb_path, cache_traverse_validate_fn);
3777 if (ret != 0) {
3778 DEBUG(10, ("winbindd_validate_cache: validation not successful.\n"));
3779 DEBUGADD(10, ("removing tdb %s.\n", tdb_path));
3780 unlink(tdb_path);
3783 done:
3784 DEBUG(10, ("winbindd_validate_cache: restoring panic function\n"));
3785 smb_panic_fn = smb_panic;
3786 return ret;
3789 /***********************************************************************
3790 Try and validate every entry in the winbindd cache.
3791 ***********************************************************************/
3793 int winbindd_validate_cache_nobackup(void)
3795 int ret = -1;
3796 const char *tdb_path = cache_path("winbindd_cache.tdb");
3798 DEBUG(10, ("winbindd_validate_cache: replacing panic function\n"));
3799 smb_panic_fn = validate_panic;
3802 if (wcache == NULL || wcache->tdb == NULL) {
3803 ret = tdb_validate_open(tdb_path, cache_traverse_validate_fn);
3804 } else {
3805 ret = tdb_validate(wcache->tdb, cache_traverse_validate_fn);
3808 if (ret != 0) {
3809 DEBUG(10, ("winbindd_validate_cache_nobackup: validation not "
3810 "successful.\n"));
3813 DEBUG(10, ("winbindd_validate_cache_nobackup: restoring panic "
3814 "function\n"));
3815 smb_panic_fn = smb_panic;
3816 return ret;
3819 bool winbindd_cache_validate_and_initialize(void)
3821 close_winbindd_cache();
3823 if (lp_winbind_offline_logon()) {
3824 if (winbindd_validate_cache() < 0) {
3825 DEBUG(0, ("winbindd cache tdb corrupt and no backup "
3826 "could be restored.\n"));
3830 return initialize_winbindd_cache();
3833 /*********************************************************************
3834 ********************************************************************/
3836 static bool add_wbdomain_to_tdc_array( struct winbindd_domain *new_dom,
3837 struct winbindd_tdc_domain **domains,
3838 size_t *num_domains )
3840 struct winbindd_tdc_domain *list = NULL;
3841 size_t idx;
3842 int i;
3843 bool set_only = false;
3845 /* don't allow duplicates */
3847 idx = *num_domains;
3848 list = *domains;
3850 for ( i=0; i< (*num_domains); i++ ) {
3851 if ( strequal( new_dom->name, list[i].domain_name ) ) {
3852 DEBUG(10,("add_wbdomain_to_tdc_array: Found existing record for %s\n",
3853 new_dom->name));
3854 idx = i;
3855 set_only = true;
3857 break;
3861 if ( !set_only ) {
3862 if ( !*domains ) {
3863 list = TALLOC_ARRAY( NULL, struct winbindd_tdc_domain, 1 );
3864 idx = 0;
3865 } else {
3866 list = TALLOC_REALLOC_ARRAY( *domains, *domains,
3867 struct winbindd_tdc_domain,
3868 (*num_domains)+1);
3869 idx = *num_domains;
3872 ZERO_STRUCT( list[idx] );
3875 if ( !list )
3876 return false;
3878 list[idx].domain_name = talloc_strdup( list, new_dom->name );
3879 list[idx].dns_name = talloc_strdup( list, new_dom->alt_name );
3881 if ( !is_null_sid( &new_dom->sid ) ) {
3882 sid_copy( &list[idx].sid, &new_dom->sid );
3883 } else {
3884 sid_copy(&list[idx].sid, &global_sid_NULL);
3887 if ( new_dom->domain_flags != 0x0 )
3888 list[idx].trust_flags = new_dom->domain_flags;
3890 if ( new_dom->domain_type != 0x0 )
3891 list[idx].trust_type = new_dom->domain_type;
3893 if ( new_dom->domain_trust_attribs != 0x0 )
3894 list[idx].trust_attribs = new_dom->domain_trust_attribs;
3896 if ( !set_only ) {
3897 *domains = list;
3898 *num_domains = idx + 1;
3901 return true;
3904 /*********************************************************************
3905 ********************************************************************/
3907 static TDB_DATA make_tdc_key( const char *domain_name )
3909 char *keystr = NULL;
3910 TDB_DATA key = { NULL, 0 };
3912 if ( !domain_name ) {
3913 DEBUG(5,("make_tdc_key: Keyname workgroup is NULL!\n"));
3914 return key;
3917 if (asprintf( &keystr, "TRUSTDOMCACHE/%s", domain_name ) == -1) {
3918 return key;
3920 key = string_term_tdb_data(keystr);
3922 return key;
3925 /*********************************************************************
3926 ********************************************************************/
3928 static int pack_tdc_domains( struct winbindd_tdc_domain *domains,
3929 size_t num_domains,
3930 unsigned char **buf )
3932 unsigned char *buffer = NULL;
3933 int len = 0;
3934 int buflen = 0;
3935 int i = 0;
3937 DEBUG(10,("pack_tdc_domains: Packing %d trusted domains\n",
3938 (int)num_domains));
3940 buflen = 0;
3942 again:
3943 len = 0;
3945 /* Store the number of array items first */
3946 len += tdb_pack( buffer+len, buflen-len, "d",
3947 num_domains );
3949 /* now pack each domain trust record */
3950 for ( i=0; i<num_domains; i++ ) {
3952 fstring tmp;
3954 if ( buflen > 0 ) {
3955 DEBUG(10,("pack_tdc_domains: Packing domain %s (%s)\n",
3956 domains[i].domain_name,
3957 domains[i].dns_name ? domains[i].dns_name : "UNKNOWN" ));
3960 len += tdb_pack( buffer+len, buflen-len, "fffddd",
3961 domains[i].domain_name,
3962 domains[i].dns_name,
3963 sid_to_fstring(tmp, &domains[i].sid),
3964 domains[i].trust_flags,
3965 domains[i].trust_attribs,
3966 domains[i].trust_type );
3969 if ( buflen < len ) {
3970 SAFE_FREE(buffer);
3971 if ( (buffer = SMB_MALLOC_ARRAY(unsigned char, len)) == NULL ) {
3972 DEBUG(0,("pack_tdc_domains: failed to alloc buffer!\n"));
3973 buflen = -1;
3974 goto done;
3976 buflen = len;
3977 goto again;
3980 *buf = buffer;
3982 done:
3983 return buflen;
3986 /*********************************************************************
3987 ********************************************************************/
3989 static size_t unpack_tdc_domains( unsigned char *buf, int buflen,
3990 struct winbindd_tdc_domain **domains )
3992 fstring domain_name, dns_name, sid_string;
3993 uint32 type, attribs, flags;
3994 int num_domains;
3995 int len = 0;
3996 int i;
3997 struct winbindd_tdc_domain *list = NULL;
3999 /* get the number of domains */
4000 len += tdb_unpack( buf+len, buflen-len, "d", &num_domains);
4001 if ( len == -1 ) {
4002 DEBUG(5,("unpack_tdc_domains: Failed to unpack domain array\n"));
4003 return 0;
4006 list = TALLOC_ARRAY( NULL, struct winbindd_tdc_domain, num_domains );
4007 if ( !list ) {
4008 DEBUG(0,("unpack_tdc_domains: Failed to talloc() domain list!\n"));
4009 return 0;
4012 for ( i=0; i<num_domains; i++ ) {
4013 len += tdb_unpack( buf+len, buflen-len, "fffddd",
4014 domain_name,
4015 dns_name,
4016 sid_string,
4017 &flags,
4018 &attribs,
4019 &type );
4021 if ( len == -1 ) {
4022 DEBUG(5,("unpack_tdc_domains: Failed to unpack domain array\n"));
4023 TALLOC_FREE( list );
4024 return 0;
4027 DEBUG(11,("unpack_tdc_domains: Unpacking domain %s (%s) "
4028 "SID %s, flags = 0x%x, attribs = 0x%x, type = 0x%x\n",
4029 domain_name, dns_name, sid_string,
4030 flags, attribs, type));
4032 list[i].domain_name = talloc_strdup( list, domain_name );
4033 list[i].dns_name = talloc_strdup( list, dns_name );
4034 if ( !string_to_sid( &(list[i].sid), sid_string ) ) {
4035 DEBUG(10,("unpack_tdc_domains: no SID for domain %s\n",
4036 domain_name));
4038 list[i].trust_flags = flags;
4039 list[i].trust_attribs = attribs;
4040 list[i].trust_type = type;
4043 *domains = list;
4045 return num_domains;
4048 /*********************************************************************
4049 ********************************************************************/
4051 static bool wcache_tdc_store_list( struct winbindd_tdc_domain *domains, size_t num_domains )
4053 TDB_DATA key = make_tdc_key( lp_workgroup() );
4054 TDB_DATA data = { NULL, 0 };
4055 int ret;
4057 if ( !key.dptr )
4058 return false;
4060 /* See if we were asked to delete the cache entry */
4062 if ( !domains ) {
4063 ret = tdb_delete( wcache->tdb, key );
4064 goto done;
4067 data.dsize = pack_tdc_domains( domains, num_domains, &data.dptr );
4069 if ( !data.dptr ) {
4070 ret = -1;
4071 goto done;
4074 ret = tdb_store( wcache->tdb, key, data, 0 );
4076 done:
4077 SAFE_FREE( data.dptr );
4078 SAFE_FREE( key.dptr );
4080 return ( ret != -1 );
4083 /*********************************************************************
4084 ********************************************************************/
4086 bool wcache_tdc_fetch_list( struct winbindd_tdc_domain **domains, size_t *num_domains )
4088 TDB_DATA key = make_tdc_key( lp_workgroup() );
4089 TDB_DATA data = { NULL, 0 };
4091 *domains = NULL;
4092 *num_domains = 0;
4094 if ( !key.dptr )
4095 return false;
4097 data = tdb_fetch( wcache->tdb, key );
4099 SAFE_FREE( key.dptr );
4101 if ( !data.dptr )
4102 return false;
4104 *num_domains = unpack_tdc_domains( data.dptr, data.dsize, domains );
4106 SAFE_FREE( data.dptr );
4108 if ( !*domains )
4109 return false;
4111 return true;
4114 /*********************************************************************
4115 ********************************************************************/
4117 bool wcache_tdc_add_domain( struct winbindd_domain *domain )
4119 struct winbindd_tdc_domain *dom_list = NULL;
4120 size_t num_domains = 0;
4121 bool ret = false;
4123 DEBUG(10,("wcache_tdc_add_domain: Adding domain %s (%s), SID %s, "
4124 "flags = 0x%x, attributes = 0x%x, type = 0x%x\n",
4125 domain->name, domain->alt_name,
4126 sid_string_dbg(&domain->sid),
4127 domain->domain_flags,
4128 domain->domain_trust_attribs,
4129 domain->domain_type));
4131 if ( !init_wcache() ) {
4132 return false;
4135 /* fetch the list */
4137 wcache_tdc_fetch_list( &dom_list, &num_domains );
4139 /* add the new domain */
4141 if ( !add_wbdomain_to_tdc_array( domain, &dom_list, &num_domains ) ) {
4142 goto done;
4145 /* pack the domain */
4147 if ( !wcache_tdc_store_list( dom_list, num_domains ) ) {
4148 goto done;
4151 /* Success */
4153 ret = true;
4154 done:
4155 TALLOC_FREE( dom_list );
4157 return ret;
4160 /*********************************************************************
4161 ********************************************************************/
4163 struct winbindd_tdc_domain * wcache_tdc_fetch_domain( TALLOC_CTX *ctx, const char *name )
4165 struct winbindd_tdc_domain *dom_list = NULL;
4166 size_t num_domains = 0;
4167 int i;
4168 struct winbindd_tdc_domain *d = NULL;
4170 DEBUG(10,("wcache_tdc_fetch_domain: Searching for domain %s\n", name));
4172 if ( !init_wcache() ) {
4173 return false;
4176 /* fetch the list */
4178 wcache_tdc_fetch_list( &dom_list, &num_domains );
4180 for ( i=0; i<num_domains; i++ ) {
4181 if ( strequal(name, dom_list[i].domain_name) ||
4182 strequal(name, dom_list[i].dns_name) )
4184 DEBUG(10,("wcache_tdc_fetch_domain: Found domain %s\n",
4185 name));
4187 d = TALLOC_P( ctx, struct winbindd_tdc_domain );
4188 if ( !d )
4189 break;
4191 d->domain_name = talloc_strdup( d, dom_list[i].domain_name );
4192 d->dns_name = talloc_strdup( d, dom_list[i].dns_name );
4193 sid_copy( &d->sid, &dom_list[i].sid );
4194 d->trust_flags = dom_list[i].trust_flags;
4195 d->trust_type = dom_list[i].trust_type;
4196 d->trust_attribs = dom_list[i].trust_attribs;
4198 break;
4202 TALLOC_FREE( dom_list );
4204 return d;
4208 /*********************************************************************
4209 ********************************************************************/
4211 void wcache_tdc_clear( void )
4213 if ( !init_wcache() )
4214 return;
4216 wcache_tdc_store_list( NULL, 0 );
4218 return;
4222 /*********************************************************************
4223 ********************************************************************/
4225 static void wcache_save_user_pwinfo(struct winbindd_domain *domain,
4226 NTSTATUS status,
4227 const DOM_SID *user_sid,
4228 const char *homedir,
4229 const char *shell,
4230 const char *gecos,
4231 uint32 gid)
4233 struct cache_entry *centry;
4234 fstring tmp;
4236 if ( (centry = centry_start(domain, status)) == NULL )
4237 return;
4239 centry_put_string( centry, homedir );
4240 centry_put_string( centry, shell );
4241 centry_put_string( centry, gecos );
4242 centry_put_uint32( centry, gid );
4244 centry_end(centry, "NSS/PWINFO/%s", sid_to_fstring(tmp, user_sid) );
4246 DEBUG(10,("wcache_save_user_pwinfo: %s\n", sid_string_dbg(user_sid) ));
4248 centry_free(centry);
4251 NTSTATUS nss_get_info_cached( struct winbindd_domain *domain,
4252 const DOM_SID *user_sid,
4253 TALLOC_CTX *ctx,
4254 ADS_STRUCT *ads, LDAPMessage *msg,
4255 const char **homedir, const char **shell,
4256 const char **gecos, gid_t *p_gid)
4258 struct winbind_cache *cache = get_cache(domain);
4259 struct cache_entry *centry = NULL;
4260 NTSTATUS nt_status;
4261 fstring tmp;
4263 if (!cache->tdb)
4264 goto do_query;
4266 centry = wcache_fetch(cache, domain, "NSS/PWINFO/%s",
4267 sid_to_fstring(tmp, user_sid));
4269 if (!centry)
4270 goto do_query;
4272 *homedir = centry_string( centry, ctx );
4273 *shell = centry_string( centry, ctx );
4274 *gecos = centry_string( centry, ctx );
4275 *p_gid = centry_uint32( centry );
4277 centry_free(centry);
4279 DEBUG(10,("nss_get_info_cached: [Cached] - user_sid %s\n",
4280 sid_string_dbg(user_sid)));
4282 return NT_STATUS_OK;
4284 do_query:
4286 nt_status = nss_get_info( domain->name, user_sid, ctx, ads, msg,
4287 homedir, shell, gecos, p_gid );
4289 DEBUG(10, ("nss_get_info returned %s\n", nt_errstr(nt_status)));
4291 if ( NT_STATUS_IS_OK(nt_status) ) {
4292 DEBUG(10, ("result:\n\thomedir = '%s'\n", *homedir));
4293 DEBUGADD(10, ("\tshell = '%s'\n", *shell));
4294 DEBUGADD(10, ("\tgecos = '%s'\n", *gecos));
4295 DEBUGADD(10, ("\tgid = '%u'\n", (unsigned int)*p_gid));
4297 wcache_save_user_pwinfo( domain, nt_status, user_sid,
4298 *homedir, *shell, *gecos, *p_gid );
4301 if ( NT_STATUS_EQUAL( nt_status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND ) ) {
4302 DEBUG(5,("nss_get_info_cached: Setting domain %s offline\n",
4303 domain->name ));
4304 set_domain_offline( domain );
4307 return nt_status;
4311 /* the cache backend methods are exposed via this structure */
4312 struct winbindd_methods cache_methods = {
4313 true,
4314 query_user_list,
4315 enum_dom_groups,
4316 enum_local_groups,
4317 name_to_sid,
4318 sid_to_name,
4319 rids_to_names,
4320 query_user,
4321 lookup_usergroups,
4322 lookup_useraliases,
4323 lookup_groupmem,
4324 sequence_number,
4325 lockout_policy,
4326 password_policy,
4327 trusted_domains
4330 static bool wcache_ndr_key(TALLOC_CTX *mem_ctx, char *domain_name,
4331 uint32_t opnum, const DATA_BLOB *req,
4332 TDB_DATA *pkey)
4334 char *key;
4335 size_t keylen;
4337 key = talloc_asprintf(mem_ctx, "NDR/%s/%d/", domain_name, (int)opnum);
4338 if (key == NULL) {
4339 return false;
4341 keylen = talloc_get_size(key) - 1;
4343 key = talloc_realloc(mem_ctx, key, char, keylen + req->length);
4344 if (key == NULL) {
4345 return false;
4347 memcpy(key + keylen, req->data, req->length);
4349 pkey->dptr = (uint8_t *)key;
4350 pkey->dsize = talloc_get_size(key);
4351 return true;
4354 static bool wcache_opnum_cacheable(uint32_t opnum)
4356 switch (opnum) {
4357 case NDR_WBINT_PING:
4358 case NDR_WBINT_QUERYSEQUENCENUMBER:
4359 case NDR_WBINT_ALLOCATEUID:
4360 case NDR_WBINT_ALLOCATEGID:
4361 return false;
4363 return true;
4366 bool wcache_fetch_ndr(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
4367 uint32_t opnum, const DATA_BLOB *req, DATA_BLOB *resp)
4369 TDB_DATA key, data;
4370 bool ret = false;
4372 if (!wcache_opnum_cacheable(opnum)) {
4373 return false;
4376 if (wcache->tdb == NULL) {
4377 return false;
4380 if (!wcache_ndr_key(talloc_tos(), domain->name, opnum, req, &key)) {
4381 return false;
4383 data = tdb_fetch(wcache->tdb, key);
4384 TALLOC_FREE(key.dptr);
4386 if (data.dptr == NULL) {
4387 return false;
4389 if (data.dsize < 4) {
4390 goto fail;
4393 if (IS_DOMAIN_ONLINE(domain)) {
4394 uint32_t entry_seqnum, dom_seqnum, last_check;
4396 if (!wcache_fetch_seqnum(domain->name, &dom_seqnum,
4397 &last_check)) {
4398 goto fail;
4400 entry_seqnum = IVAL(data.dptr, 0);
4401 if (entry_seqnum != dom_seqnum) {
4402 DEBUG(10, ("Entry has wrong sequence number: %d\n",
4403 (int)entry_seqnum));
4404 goto fail;
4408 resp->data = (uint8_t *)talloc_memdup(mem_ctx, data.dptr + 4,
4409 data.dsize - 4);
4410 if (resp->data == NULL) {
4411 DEBUG(10, ("talloc failed\n"));
4412 goto fail;
4414 resp->length = data.dsize - 4;
4416 ret = true;
4417 fail:
4418 SAFE_FREE(data.dptr);
4419 return ret;
4422 void wcache_store_ndr(struct winbindd_domain *domain, uint32_t opnum,
4423 const DATA_BLOB *req, const DATA_BLOB *resp)
4425 TDB_DATA key, data;
4426 uint32_t dom_seqnum, last_check;
4428 if (!wcache_opnum_cacheable(opnum)) {
4429 return;
4432 if (wcache->tdb == NULL) {
4433 return;
4436 if (!wcache_fetch_seqnum(domain->name, &dom_seqnum, &last_check)) {
4437 DEBUG(10, ("could not fetch seqnum for domain %s\n",
4438 domain->name));
4439 return;
4442 if (!wcache_ndr_key(talloc_tos(), domain->name, opnum, req, &key)) {
4443 return;
4446 data.dsize = resp->length + 4;
4447 data.dptr = talloc_array(key.dptr, uint8_t, data.dsize);
4448 if (data.dptr == NULL) {
4449 goto done;
4452 SIVAL(data.dptr, 0, dom_seqnum);
4453 memcpy(data.dptr+4, resp->data, resp->length);
4455 tdb_store(wcache->tdb, key, data, 0);
4457 done:
4458 TALLOC_FREE(key.dptr);
4459 return;