net: fix net cache samlogon list output
[samba.git] / source3 / utils / net_cache.c
1 /*
2    Samba Unix/Linux SMB client library
3    Distributed SMB/CIFS Server Management Utility
4    Copyright (C) Rafal Szczesniak    2002
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "net.h"
22 #include "libsmb/samlogon_cache.h"
23 #include "../librpc/gen_ndr/netlogon.h"
24 #include "../librpc/gen_ndr/ndr_netlogon.h"
25 #include "libcli/security/dom_sid.h"
26
27 /**
28  * @file net_cache.c
29  * @brief This is part of the net tool which is basically command
30  *        line wrapper for gencache.c functions (mainly for testing)
31  *
32  **/
33
34
35 /*
36  * These routines are used via gencache_iterate() to display the cache's contents
37  * (print_cache_entry) and to flush it (delete_cache_entry).
38  * Both of them are defined by first arg of gencache_iterate() routine.
39  */
40 static void print_cache_entry(const char* keystr, DATA_BLOB value,
41                               const time_t timeout, void* dptr)
42 {
43         char *timeout_str;
44         char *alloc_str = NULL;
45         const char *datastr;
46         char *datastr_free = NULL;
47         time_t now_t = time(NULL);
48         struct tm timeout_tm, now_tm;
49         struct tm *ptimeout_tm, *pnow_tm;
50
51         ptimeout_tm = localtime_r(&timeout, &timeout_tm);
52         if (ptimeout_tm == NULL) {
53                 return;
54         }
55         pnow_tm = localtime_r(&now_t, &now_tm);
56         if (pnow_tm == NULL) {
57                 return;
58         }
59
60         /* form up timeout string depending whether it's today's date or not */
61         if (timeout_tm.tm_year != now_tm.tm_year ||
62                         timeout_tm.tm_mon != now_tm.tm_mon ||
63                         timeout_tm.tm_mday != now_tm.tm_mday) {
64
65                 timeout_str = asctime(&timeout_tm);
66                 if (!timeout_str) {
67                         return;
68                 }
69                 timeout_str[strlen(timeout_str) - 1] = '\0';    /* remove tailing CR */
70         } else {
71                 if (asprintf(&alloc_str, "%.2d:%.2d:%.2d", timeout_tm.tm_hour,
72                          timeout_tm.tm_min, timeout_tm.tm_sec) == -1) {
73                         return;
74                 }
75                 timeout_str = alloc_str;
76         }
77
78         datastr = (char *)value.data;
79
80         if ((value.length > 0) && (value.data[value.length-1] != '\0')) {
81                 datastr_free = talloc_asprintf(
82                         talloc_tos(), "<binary length %d>",
83                         (int)value.length);
84                 datastr = datastr_free;
85                 if (datastr == NULL) {
86                         datastr = "<binary>";
87                 }
88         }
89
90         d_printf(_("Key: %s\t Timeout: %s\t Value: %s  %s\n"), keystr,
91                  timeout_str, datastr, timeout > now_t ? "": _("(expired)"));
92
93         SAFE_FREE(alloc_str);
94 }
95
96 static void delete_cache_entry(const char* keystr, const char* datastr,
97                                const time_t timeout, void* dptr)
98 {
99         if (!gencache_del(keystr))
100                 d_fprintf(stderr, _("Couldn't delete entry! key = %s\n"),
101                           keystr);
102 }
103
104
105 /**
106  * Parse text representation of timeout value
107  *
108  * @param timeout_str string containing text representation of the timeout
109  * @return numeric timeout of time_t type
110  **/
111 static time_t parse_timeout(const char* timeout_str)
112 {
113         char sign = '\0', *number = NULL, unit = '\0';
114         int len, number_begin, number_end;
115         time_t timeout;
116
117         /* sign detection */
118         if (timeout_str[0] == '!' || timeout_str[0] == '+') {
119                 sign = timeout_str[0];
120                 number_begin = 1;
121         } else {
122                 number_begin = 0;
123         }
124
125         /* unit detection */
126         len = strlen(timeout_str);
127         switch (timeout_str[len - 1]) {
128         case 's':
129         case 'm':
130         case 'h':
131         case 'd':
132         case 'w': unit = timeout_str[len - 1];
133         }
134
135         /* number detection */
136         len = (sign) ? strlen(&timeout_str[number_begin]) : len;
137         number_end = (unit) ? len - 1 : len;
138         number = SMB_STRNDUP(&timeout_str[number_begin], number_end);
139
140         /* calculate actual timeout value */
141         timeout = (time_t)atoi(number);
142
143         switch (unit) {
144         case 'm': timeout *= 60; break;
145         case 'h': timeout *= 60*60; break;
146         case 'd': timeout *= 60*60*24; break;
147         case 'w': timeout *= 60*60*24*7; break;  /* that's fair enough, I think :) */
148         }
149
150         switch (sign) {
151         case '!': timeout = time(NULL) - timeout; break;
152         case '+':
153         default:  timeout += time(NULL); break;
154         }
155
156         if (number) SAFE_FREE(number);
157         return timeout;
158 }
159
160
161 /**
162  * Add an entry to the cache. If it does exist, then set it.
163  *
164  * @param c     A net_context structure
165  * @param argv key, value and timeout are passed in command line
166  * @return 0 on success, otherwise failure
167  **/
168 static int net_cache_add(struct net_context *c, int argc, const char **argv)
169 {
170         const char *keystr, *datastr, *timeout_str;
171         time_t timeout;
172
173         if (argc < 3 || c->display_usage) {
174                 d_printf("%s\n%s",
175                          _("Usage:"),
176                          _("net cache add <key string> <data string> "
177                            "<timeout>\n"));
178                 return -1;
179         }
180
181         keystr = argv[0];
182         datastr = argv[1];
183         timeout_str = argv[2];
184
185         /* parse timeout given in command line */
186         timeout = parse_timeout(timeout_str);
187         if (!timeout) {
188                 d_fprintf(stderr, _("Invalid timeout argument.\n"));
189                 return -1;
190         }
191
192         if (gencache_set(keystr, datastr, timeout)) {
193                 d_printf(_("New cache entry stored successfully.\n"));
194                 return 0;
195         }
196
197         d_fprintf(stderr, _("Entry couldn't be added. Perhaps there's already such a key.\n"));
198         return -1;
199 }
200
201 /**
202  * Delete an entry in the cache
203  *
204  * @param c     A net_context structure
205  * @param argv key to delete an entry of
206  * @return 0 on success, otherwise failure
207  **/
208 static int net_cache_del(struct net_context *c, int argc, const char **argv)
209 {
210         const char *keystr = argv[0];
211
212         if (argc < 1 || c->display_usage) {
213                 d_printf("%s\n%s",
214                          _("Usage:"),
215                          _(" net cache del <key string>\n"));
216                 return -1;
217         }
218
219         if(gencache_del(keystr)) {
220                 d_printf(_("Entry deleted.\n"));
221                 return 0;
222         }
223
224         d_fprintf(stderr, _("Couldn't delete specified entry\n"));
225         return -1;
226 }
227
228
229 /**
230  * Get and display an entry from the cache
231  *
232  * @param c     A net_context structure
233  * @param argv key to search an entry of
234  * @return 0 on success, otherwise failure
235  **/
236 static int net_cache_get(struct net_context *c, int argc, const char **argv)
237 {
238         const char* keystr = argv[0];
239         DATA_BLOB value;
240         time_t timeout;
241
242         if (argc < 1 || c->display_usage) {
243                 d_printf("%s\n%s",
244                          _("Usage:"),
245                          _(" net cache get <key>\n"));
246                 return -1;
247         }
248
249         if (gencache_get_data_blob(keystr, NULL, &value, &timeout, NULL)) {
250                 print_cache_entry(keystr, value, timeout, NULL);
251                 data_blob_free(&value);
252                 return 0;
253         }
254
255         d_fprintf(stderr, _("Failed to find entry\n"));
256         return -1;
257 }
258
259
260 /**
261  * Search an entry/entries in the cache
262  *
263  * @param c     A net_context structure
264  * @param argv key pattern to match the entries to
265  * @return 0 on success, otherwise failure
266  **/
267 static int net_cache_search(struct net_context *c, int argc, const char **argv)
268 {
269         const char* pattern;
270
271         if (argc < 1 || c->display_usage) {
272                 d_printf("%s\n%s",
273                          _("Usage:"),
274                          _(" net cache search <pattern>\n"));
275                 return -1;
276         }
277
278         pattern = argv[0];
279         gencache_iterate_blobs(print_cache_entry, NULL, pattern);
280         return 0;
281 }
282
283
284 /**
285  * List the contents of the cache
286  *
287  * @param c     A net_context structure
288  * @param argv ignored in this functionailty
289  * @return always returns 0
290  **/
291 static int net_cache_list(struct net_context *c, int argc, const char **argv)
292 {
293         const char* pattern = "*";
294
295         if (c->display_usage) {
296                 d_printf(  "%s\n"
297                            "net cache list\n"
298                            "    %s\n",
299                          _("Usage:"),
300                          _("List all cache entries."));
301                 return 0;
302         }
303         gencache_iterate_blobs(print_cache_entry, NULL, pattern);
304         return 0;
305 }
306
307
308 /**
309  * Flush the whole cache
310  *
311  * @param c     A net_context structure
312  * @param argv ignored in this functionality
313  * @return always returns 0
314  **/
315 static int net_cache_flush(struct net_context *c, int argc, const char **argv)
316 {
317         const char* pattern = "*";
318         if (c->display_usage) {
319                 d_printf(  "%s\n"
320                            "net cache flush\n"
321                            "    %s",
322                          _("Usage:"),
323                          _("Delete all cache entries."));
324                 return 0;
325         }
326         gencache_iterate(delete_cache_entry, NULL, pattern);
327         return 0;
328 }
329
330 static int net_cache_stabilize(struct net_context *c, int argc,
331                                const char **argv)
332 {
333         if (c->display_usage) {
334                 d_printf(  "%s\n"
335                            "net cache stabilize\n"
336                            "    %s\n",
337                          _("Usage:"),
338                          _("Move transient cache content to stable storage"));
339                 return 0;
340         }
341
342         if (!gencache_stabilize()) {
343                 return -1;
344         }
345         return 0;
346 }
347
348 static int netsamlog_cache_for_all_cb(const char *sid_str,
349                                       time_t when_cached,
350                                       struct netr_SamInfo3 *info3,
351                                       void *private_data)
352 {
353         struct net_context *c = (struct net_context *)private_data;
354         char *name = NULL;
355
356         name = talloc_asprintf(c, "%s\\%s",
357                                info3->base.logon_domain.string,
358                                info3->base.account_name.string);
359         if (name == NULL) {
360                 return -1;
361         }
362
363         d_printf("%-50s %-40s %s\n",
364                  sid_str,
365                  name,
366                  timestring(c, when_cached));
367
368         return 0;
369 }
370
371 static int net_cache_samlogon_list(struct net_context *c,
372                                    int argc,
373                                    const char **argv)
374 {
375         int ret;
376
377         d_printf("%-50s %-40s When cached\n", "SID", "Name");
378         d_printf("------------------------------------------------------------"
379                  "------------------------------------------------------------"
380                  "----\n");
381
382         ret = netsamlog_cache_for_all(netsamlog_cache_for_all_cb, c);
383         if (ret == -1) {
384                 return -1;
385         }
386
387         return 0;
388 }
389
390 static int net_cache_samlogon_show(struct net_context *c,
391                                    int argc,
392                                    const char **argv)
393 {
394         const char *sid_str = argv[0];
395         struct dom_sid sid;
396         struct dom_sid *user_sids = NULL;
397         uint32_t num_user_sids;
398         struct netr_SamInfo3 *info3 = NULL;
399         char *name = NULL;
400         uint32_t i;
401         NTSTATUS status;
402         bool ok;
403
404         if (argc != 1 || c->display_usage) {
405                 d_printf("%s\n"
406                          "net cache samlogon show SID\n"
407                          "    %s\n",
408                          _("Usage:"),
409                          _("Show samlogon cache entry for SID."));
410                 return 0;
411         }
412
413         ok = string_to_sid(&sid, sid_str);
414         if (!ok) {
415                 d_printf("String to SID failed for %s\n", sid_str);
416                 return -1;
417         }
418
419         info3 = netsamlogon_cache_get(c, &sid);
420         if (info3 == NULL) {
421                 d_printf("SID %s not found in samlogon cache\n", sid_str);
422                 return -1;
423         }
424
425         name = talloc_asprintf(c, "%s\\%s",
426                                info3->base.logon_domain.string,
427                                info3->base.account_name.string);
428         if (name == NULL) {
429                 return -1;
430         }
431
432         d_printf("Name: %s\n", name);
433
434         status = sid_array_from_info3(c,
435                                       info3,
436                                       &user_sids,
437                                       &num_user_sids,
438                                       true);
439         if (!NT_STATUS_IS_OK(status)) {
440                 d_printf("sid_array_from_info3 failed for %s\n", sid_str);
441                 return -1;
442         }
443
444         for (i = 0; i < num_user_sids; i++) {
445                 d_printf("SID %2" PRIu32 ": %s\n",
446                          i, sid_string_dbg(&user_sids[i]));
447         }
448
449         return 0;
450 }
451
452 static int net_cache_samlogon_ndrdump(struct net_context *c,
453                                       int argc,
454                                       const char **argv)
455 {
456         const char *sid_str = NULL;
457         struct dom_sid sid;
458         struct netr_SamInfo3 *info3 = NULL;
459         struct ndr_print *ndr_print = NULL;
460         bool ok;
461
462         if (argc != 1 || c->display_usage) {
463                 d_printf(  "%s\n"
464                            "net cache samlogon ndrdump SID\n"
465                            "    %s\n",
466                            _("Usage:"),
467                            _("Show samlogon cache entry for SID."));
468                 return 0;
469         }
470
471         sid_str = argv[0];
472
473         ok = string_to_sid(&sid, sid_str);
474         if (!ok) {
475                 d_printf("String to SID failed for %s\n", sid_str);
476                 return -1;
477         }
478
479         info3 = netsamlogon_cache_get(c, &sid);
480         if (info3 == NULL) {
481                 d_printf("SID %s not found in samlogon cache\n", sid_str);
482                 return -1;
483         }
484
485         ndr_print = talloc_zero(c, struct ndr_print);
486         if (ndr_print == NULL) {
487                 d_printf("Could not allocate memory.\n");
488                 return -1;
489         }
490
491         ndr_print->print = ndr_print_printf_helper;
492         ndr_print->depth = 1;
493         ndr_print_netr_SamInfo3(ndr_print, "netr_SamInfo3", info3);
494         TALLOC_FREE(ndr_print);
495
496         return 0;
497 }
498
499 static int net_cache_samlogon_delete(struct net_context *c,
500                                      int argc,
501                                      const char **argv)
502 {
503         const char *sid_str = argv[0];
504         struct dom_sid sid;
505         bool ok;
506
507         if (argc != 1 || c->display_usage) {
508                 d_printf(  "%s\n"
509                            "net cache samlogon delete SID\n"
510                            "    %s\n",
511                          _("Usage:"),
512                          _("Delete samlogon cache entry for SID."));
513                 return 0;
514         }
515
516         ok = string_to_sid(&sid, sid_str);
517         if (!ok) {
518                 d_printf("String to SID failed for %s\n", sid_str);
519                 return -1;
520         }
521
522         netsamlogon_clear_cached_user(&sid);
523
524         return 0;
525 }
526
527 static int net_cache_samlogon(struct net_context *c, int argc, const char **argv)
528 {
529         struct functable func[] = {
530                 {
531                         "list",
532                         net_cache_samlogon_list,
533                         NET_TRANSPORT_LOCAL,
534                         N_("List samlogon cache"),
535                         N_("net cache samlogon list\n"
536                            "    List samlogon cachen\n")
537                 },
538                 {
539                         "show",
540                         net_cache_samlogon_show,
541                         NET_TRANSPORT_LOCAL,
542                         N_("Show samlogon cache entry"),
543                         N_("net cache samlogon show SID\n"
544                            "    Show samlogon cache entry\n")
545                 },
546                 {
547                         "ndrdump",
548                         net_cache_samlogon_ndrdump,
549                         NET_TRANSPORT_LOCAL,
550                         N_("Dump the samlogon cache entry NDR blob"),
551                         N_("net cache samlogon ndrdump SID\n"
552                            "    Dump the samlogon cache entry NDR blob\n")
553                 },
554                 {
555                         "delete",
556                         net_cache_samlogon_delete,
557                         NET_TRANSPORT_LOCAL,
558                         N_("Delete samlogon cache entry"),
559                         N_("net cache samlogon delete SID\n"
560                            "    Delete samlogon cache entry\n")
561                 },
562                 {NULL, NULL, 0, NULL, NULL}
563         };
564
565         return net_run_function(c, argc, argv, "net cache samlogon", func);
566 }
567
568 /**
569  * Entry point to 'net cache' subfunctionality
570  *
571  * @param c     A net_context structure
572  * @param argv arguments passed to further called functions
573  * @return whatever further functions return
574  **/
575 int net_cache(struct net_context *c, int argc, const char **argv)
576 {
577         struct functable func[] = {
578                 {
579                         "add",
580                         net_cache_add,
581                         NET_TRANSPORT_LOCAL,
582                         N_("Add new cache entry"),
583                         N_("net cache add <key string> <data string> <timeout>\n"
584                            "  Add new cache entry.\n"
585                            "    key string\tKey string to add cache data under.\n"
586                            "    data string\tData to store under given key.\n"
587                            "    timeout\tTimeout for cache data.")
588                 },
589                 {
590                         "del",
591                         net_cache_del,
592                         NET_TRANSPORT_LOCAL,
593                         N_("Delete existing cache entry by key"),
594                         N_("net cache del <key string>\n"
595                            "  Delete existing cache entry by key.\n"
596                            "    key string\tKey string to delete.")
597                 },
598                 {
599                         "get",
600                         net_cache_get,
601                         NET_TRANSPORT_LOCAL,
602                         N_("Get cache entry by key"),
603                         N_("net cache get <key string>\n"
604                            "  Get cache entry by key.\n"
605                            "    key string\tKey string to look up cache entry for.")
606
607                 },
608                 {
609                         "search",
610                         net_cache_search,
611                         NET_TRANSPORT_LOCAL,
612                         N_("Search entry by pattern"),
613                         N_("net cache search <pattern>\n"
614                            "  Search entry by pattern.\n"
615                            "    pattern\tPattern to search for in cache.")
616                 },
617                 {
618                         "list",
619                         net_cache_list,
620                         NET_TRANSPORT_LOCAL,
621                         N_("List all cache entries"),
622                         N_("net cache list\n"
623                            "  List all cache entries")
624                 },
625                 {
626                         "flush",
627                         net_cache_flush,
628                         NET_TRANSPORT_LOCAL,
629                         N_("Delete all cache entries"),
630                         N_("net cache flush\n"
631                            "  Delete all cache entries")
632                 },
633                 {
634                         "stabilize",
635                         net_cache_stabilize,
636                         NET_TRANSPORT_LOCAL,
637                         N_("Move transient cache content to stable storage"),
638                         N_("net cache stabilize\n"
639                            "  Move transient cache content to stable storage")
640                 },
641                 {
642                         "samlogon",
643                         net_cache_samlogon,
644                         NET_TRANSPORT_LOCAL,
645                         N_("List contents of the samlogon cache"),
646                         N_("net cache samlogon\n"
647                            "  List contents of the samlogon cache")
648                 },
649                 {NULL, NULL, 0, NULL, NULL}
650         };
651
652         return net_run_function(c, argc, argv, "net cache", func);
653 }