Change all uses of uint32/16/8 in proto.h to uint32_t/16_t/8_t.
[kamenim/samba-autobuild/.git] / source3 / libsmb / trustdom_cache.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Trusted domain names cache on top of gencache.
5
6    Copyright (C) Rafal Szczesniak       2002
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "../libcli/security/security.h"
24 #include "../librpc/gen_ndr/ndr_lsa_c.h"
25 #include "libsmb/libsmb.h"
26 #include "rpc_client/cli_pipe.h"
27 #include "rpc_client/cli_lsarpc.h"
28
29 #undef DBGC_CLASS
30 #define DBGC_CLASS DBGC_ALL     /* there's no proper class yet */
31
32 #define TDOMKEY_FMT  "TDOM/%s"
33 #define TDOMTSKEY    "TDOMCACHE/TIMESTAMP"
34
35
36 /**
37  * @file trustdom_cache.c
38  *
39  * Implementation of trusted domain names cache useful when
40  * samba acts as domain member server. In such case, caching
41  * domain names currently trusted gives a performance gain
42  * because there's no need to query PDC each time we need
43  * list of trusted domains
44  **/
45
46 /**
47  * Initialise trustdom name caching system. Call gencache
48  * initialisation routine to perform necessary activities.
49  *
50  * @return true upon successful cache initialisation or
51  *         false if cache init failed
52  **/
53
54 bool trustdom_cache_enable(void)
55 {
56         return True;
57 }
58
59
60 /**
61  * Shutdown trustdom name caching system. Calls gencache
62  * shutdown function.
63  *
64  * @return true upon successful cache close or
65  *         false if it failed
66  **/
67
68 bool trustdom_cache_shutdown(void)
69 {
70         return True;
71 }
72
73
74 /**
75  * Form up trustdom name key. It is based only
76  * on domain name now.
77  *
78  * @param name trusted domain name
79  * @return cache key for use in gencache mechanism
80  **/
81
82 static char* trustdom_cache_key(const char* name)
83 {
84         char* keystr = NULL;
85         asprintf_strupper_m(&keystr, TDOMKEY_FMT, name);
86
87         return keystr;
88 }
89
90
91 /**
92  * Store trusted domain in gencache as the domain name (key)
93  * and trusted domain's SID (value)
94  *
95  * @param name trusted domain name
96  * @param alt_name alternative trusted domain name (used in ADS domains)
97  * @param sid trusted domain's SID
98  * @param timeout cache entry expiration time
99  * @return true upon successful value storing or
100  *         false if store attempt failed
101  **/
102  
103 bool trustdom_cache_store(const char *name, const char *alt_name,
104                           const struct dom_sid *sid, time_t timeout)
105 {
106         char *key, *alt_key;
107         fstring sid_string;
108         bool ret;
109
110         DEBUG(5, ("trustdom_store: storing SID %s of domain %s\n",
111                   sid_string_dbg(sid), name));
112
113         key = trustdom_cache_key(name);
114         alt_key = alt_name ? trustdom_cache_key(alt_name) : NULL;
115
116         /* Generate string representation domain SID */
117         sid_to_fstring(sid_string, sid);
118
119         /*
120          * try to put the names in the cache
121          */
122         if (alt_key) {
123                 ret = gencache_set(alt_key, sid_string, timeout);
124                 if ( ret ) {
125                         ret = gencache_set(key, sid_string, timeout);
126                 }
127                 SAFE_FREE(alt_key);
128                 SAFE_FREE(key);
129                 return ret;
130         }
131
132         ret = gencache_set(key, sid_string, timeout);
133         SAFE_FREE(key);
134         return ret;
135 }
136
137
138 /**
139  * Fetch trusted domain's SID from the gencache.
140  * This routine can also be used to check whether given
141  * domain is currently trusted one.
142  *
143  * @param name trusted domain name
144  * @param sid trusted domain's SID to be returned
145  * @return true if entry is found or
146  *         false if has expired/doesn't exist
147  **/
148
149 bool trustdom_cache_fetch(const char* name, struct dom_sid* sid)
150 {
151         char *key = NULL, *value = NULL;
152         time_t timeout;
153
154         /* exit now if null pointers were passed as they're required further */
155         if (!sid)
156                 return False;
157
158         /* prepare a key and get the value */
159         key = trustdom_cache_key(name);
160         if (!key)
161                 return False;
162
163         if (!gencache_get(key, talloc_tos(), &value, &timeout)) {
164                 DEBUG(5, ("no entry for trusted domain %s found.\n", name));
165                 SAFE_FREE(key);
166                 return False;
167         } else {
168                 SAFE_FREE(key);
169                 DEBUG(5, ("trusted domain %s found (%s)\n", name, value));
170         }
171
172         /* convert sid string representation into struct dom_sid structure */
173         if(! string_to_sid(sid, value)) {
174                 sid = NULL;
175                 TALLOC_FREE(value);
176                 return False;
177         }
178
179         TALLOC_FREE(value);
180         return True;
181 }
182
183
184 /*******************************************************************
185  fetch the timestamp from the last update 
186 *******************************************************************/
187
188 uint32_t trustdom_cache_fetch_timestamp( void )
189 {
190         char *value = NULL;
191         time_t timeout;
192         uint32_t timestamp;
193
194         if (!gencache_get(TDOMTSKEY, talloc_tos(), &value, &timeout)) {
195                 DEBUG(5, ("no timestamp for trusted domain cache located.\n"));
196                 SAFE_FREE(value);
197                 return 0;
198         } 
199
200         timestamp = atoi(value);
201
202         TALLOC_FREE(value);
203         return timestamp;
204 }
205
206 /*******************************************************************
207  store the timestamp from the last update 
208 *******************************************************************/
209
210 bool trustdom_cache_store_timestamp( uint32_t t, time_t timeout )
211 {
212         fstring value;
213
214         fstr_sprintf(value, "%d", t );
215
216         if (!gencache_set(TDOMTSKEY, value, timeout)) {
217                 DEBUG(5, ("failed to set timestamp for trustdom_cache\n"));
218                 return False;
219         } 
220
221         return True;
222 }
223
224
225 /**
226  * Delete single trustdom entry. Look at the
227  * gencache_iterate definition.
228  *
229  **/
230
231 static void flush_trustdom_name(const char* key, const char *value, time_t timeout, void* dptr)
232 {
233         gencache_del(key);
234         DEBUG(5, ("Deleting entry %s\n", key));
235 }
236
237
238 /**
239  * Flush all the trusted domains entries from the cache.
240  **/
241
242 void trustdom_cache_flush(void)
243 {
244         /* 
245          * iterate through each TDOM cache's entry and flush it
246          * by flush_trustdom_name function
247          */
248         gencache_iterate(flush_trustdom_name, NULL, trustdom_cache_key("*"));
249         DEBUG(5, ("Trusted domains cache flushed\n"));
250 }
251
252 /*********************************************************************
253  Enumerate the list of trusted domains from a DC
254 *********************************************************************/
255
256 static bool enumerate_domain_trusts( TALLOC_CTX *mem_ctx, const char *domain,
257                                      char ***domain_names, uint32_t *num_domains,
258                                      struct dom_sid **sids )
259 {
260         struct policy_handle    pol;
261         NTSTATUS status, result;
262         fstring         dc_name;
263         struct sockaddr_storage dc_ss;
264         uint32_t                enum_ctx = 0;
265         struct cli_state *cli = NULL;
266         struct rpc_pipe_client *lsa_pipe = NULL;
267         struct lsa_DomainList dom_list;
268         int i;
269         struct dcerpc_binding_handle *b = NULL;
270
271         *domain_names = NULL;
272         *num_domains = 0;
273         *sids = NULL;
274
275         /* lookup a DC first */
276
277         if ( !get_dc_name(domain, NULL, dc_name, &dc_ss) ) {
278                 DEBUG(3,("enumerate_domain_trusts: can't locate a DC for domain %s\n",
279                         domain));
280                 return False;
281         }
282
283         /* setup the anonymous connection */
284
285         status = cli_full_connection( &cli, lp_netbios_name(), dc_name, &dc_ss, 0, "IPC$", "IPC",
286                 "", "", "", 0, Undefined);
287         if ( !NT_STATUS_IS_OK(status) )
288                 goto done;
289
290         /* open the LSARPC_PIPE */
291
292         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
293                                           &lsa_pipe);
294         if (!NT_STATUS_IS_OK(status)) {
295                 goto done;
296         }
297
298         b = lsa_pipe->binding_handle;
299
300         /* get a handle */
301
302         status = rpccli_lsa_open_policy(lsa_pipe, mem_ctx, True,
303                 LSA_POLICY_VIEW_LOCAL_INFORMATION, &pol);
304         if ( !NT_STATUS_IS_OK(status) )
305                 goto done;
306
307         /* Lookup list of trusted domains */
308
309         status = dcerpc_lsa_EnumTrustDom(b, mem_ctx,
310                                          &pol,
311                                          &enum_ctx,
312                                          &dom_list,
313                                          (uint32_t)-1,
314                                          &result);
315         if ( !NT_STATUS_IS_OK(status) )
316                 goto done;
317         if (!NT_STATUS_IS_OK(result)) {
318                 status = result;
319                 goto done;
320         }
321
322         *num_domains = dom_list.count;
323
324         *domain_names = talloc_zero_array(mem_ctx, char *, *num_domains);
325         if (!*domain_names) {
326                 status = NT_STATUS_NO_MEMORY;
327                 goto done;
328         }
329
330         *sids = talloc_zero_array(mem_ctx, struct dom_sid, *num_domains);
331         if (!*sids) {
332                 status = NT_STATUS_NO_MEMORY;
333                 goto done;
334         }
335
336         for (i=0; i< *num_domains; i++) {
337                 (*domain_names)[i] = discard_const_p(char, dom_list.domains[i].name.string);
338                 (*sids)[i] = *dom_list.domains[i].sid;
339         }
340
341 done:
342         /* cleanup */
343         if (cli) {
344                 DEBUG(10,("enumerate_domain_trusts: shutting down connection...\n"));
345                 cli_shutdown( cli );
346         }
347
348         return NT_STATUS_IS_OK(status);
349 }
350
351 /********************************************************************
352  update the trustdom_cache if needed 
353 ********************************************************************/
354 #define TRUSTDOM_UPDATE_INTERVAL        600
355
356 void update_trustdom_cache( void )
357 {
358         char **domain_names;
359         struct dom_sid *dom_sids;
360         uint32_t num_domains;
361         uint32_t last_check;
362         int time_diff;
363         TALLOC_CTX *mem_ctx = NULL;
364         time_t now = time(NULL);
365         int i;
366
367         /* get the timestamp.  We have to initialise it if the last timestamp == 0 */   
368         if ( (last_check = trustdom_cache_fetch_timestamp()) == 0 ) 
369                 trustdom_cache_store_timestamp(0, now+TRUSTDOM_UPDATE_INTERVAL);
370
371         time_diff = (int) (now - last_check);
372
373         if ( (time_diff > 0) && (time_diff < TRUSTDOM_UPDATE_INTERVAL) ) {
374                 DEBUG(10,("update_trustdom_cache: not time to update trustdom_cache yet\n"));
375                 return;
376         }
377
378         /* note that we don't lock the timestamp. This prevents this
379            smbd from blocking all other smbd daemons while we
380            enumerate the trusted domains */
381         trustdom_cache_store_timestamp(now, now+TRUSTDOM_UPDATE_INTERVAL);
382
383         if ( !(mem_ctx = talloc_init("update_trustdom_cache")) ) {
384                 DEBUG(0,("update_trustdom_cache: talloc_init() failed!\n"));
385                 goto done;
386         }
387
388         /* get the domains and store them */
389
390         if ( enumerate_domain_trusts(mem_ctx, lp_workgroup(), &domain_names, 
391                 &num_domains, &dom_sids)) {
392                 for ( i=0; i<num_domains; i++ ) {
393                         trustdom_cache_store( domain_names[i], NULL, &dom_sids[i], 
394                                 now+TRUSTDOM_UPDATE_INTERVAL);
395                 }               
396         } else {
397                 /* we failed to fetch the list of trusted domains - restore the old
398                    timestamp */
399                 trustdom_cache_store_timestamp(last_check, 
400                                                last_check+TRUSTDOM_UPDATE_INTERVAL);
401         }
402
403 done:   
404         talloc_destroy( mem_ctx );
405
406         return;
407 }