48251c33ea4a038f22b80749067c8b3c9c3bd8c9
[bbaumbach/samba-autobuild/.git] / source4 / lib / registry / tools / regshell.c
1 /*
2    Unix SMB/CIFS implementation.
3    simple registry frontend
4
5    Copyright (C) Jelmer Vernooij 2004-2007
6    Copyright (C) Wilco Baan Hofman 2009
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 "lib/registry/registry.h"
24 #include "lib/cmdline/popt_common.h"
25 #include "lib/events/events.h"
26 #include "system/time.h"
27 #include "../libcli/smbreadline/smbreadline.h"
28 #include "librpc/gen_ndr/ndr_security.h"
29 #include "lib/registry/tools/common.h"
30 #include "param/param.h"
31
32 struct regshell_context {
33         struct registry_context *registry;
34         char *path;
35         char *predef;
36         struct registry_key *current;
37         struct registry_key *root;
38 };
39
40 static WERROR get_full_path(struct regshell_context *ctx, const char *path, char **ret_path)
41 {
42         const char *dir;
43         char *tmp;
44         char *new_path;
45
46         if (path[0] == '\\') {
47                 new_path = talloc_strdup(ctx, "");
48         } else {
49                 new_path = talloc_strdup(ctx, ctx->path);
50         }               
51
52         dir = strtok(discard_const_p(char, path), "\\");
53         if (dir == NULL) {
54                 *ret_path = new_path;
55                 return WERR_OK;
56         }
57         do {
58                 if (strcmp(dir, "..") == 0) {
59                         if (strchr(new_path, '\\')) {
60                                 new_path[strrchr(new_path, '\\') - new_path] = '\0';
61                         } else {
62                                 tmp = new_path;
63                                 new_path = talloc_strdup(ctx, "");
64                                 talloc_free(tmp);
65                         }
66                         continue;
67                 } 
68                 if (strcmp(dir, ".") == 0) {
69                         continue;
70                 }
71
72                 tmp = new_path;
73                 /* No prepending a backslash */
74                 if (strcmp(new_path, "") == 0) {
75                         new_path = talloc_strdup(ctx, dir);
76                 } else {
77                         new_path = talloc_asprintf(ctx, "%s\\%s", new_path, dir);
78                 }
79                 talloc_free(tmp);
80                 
81         } while ((dir = strtok(NULL, "\\")));
82
83         *ret_path = new_path;
84         return WERR_OK;
85 }
86
87 /* *
88  * ck/cd - change key
89  * ls - list values/keys
90  * rmval/rm - remove value
91  * rmkey/rmdir - remove key
92  * mkkey/mkdir - make key
93  * ch - change hive
94  * info - show key info
95  * save - save hive
96  * print - print value
97  * help
98  * exit
99  */
100
101 static WERROR cmd_info(struct regshell_context *ctx, int argc, const char **argv)
102 {
103         struct security_descriptor *sec_desc = NULL;
104         time_t last_mod;
105         WERROR error;
106         const char *classname = NULL;
107         NTTIME last_change;
108         uint32_t max_subkeynamelen;
109         uint32_t max_valnamelen;
110         uint32_t max_valbufsize;
111         uint32_t num_subkeys;
112         uint32_t num_values;
113
114         error = reg_key_get_info(ctx, ctx->current, &classname, &num_subkeys, &num_values,
115                                  &last_change, &max_subkeynamelen, &max_valnamelen, &max_valbufsize);
116         if (!W_ERROR_IS_OK(error)) {
117                 printf("Error getting key info: %s\n", win_errstr(error));
118                 return error;
119         }
120
121
122         printf("Name: %s\n", strchr(ctx->path, '\\')?strrchr(ctx->path, '\\')+1:
123                    ctx->path);
124         printf("Full path: %s\n", ctx->path);
125         if (classname != NULL)
126                 printf("Key Class: %s\n", classname);
127         last_mod = nt_time_to_unix(last_change);
128         printf("Time Last Modified: %s", ctime(&last_mod));
129         printf("Number of subkeys: %d\n", num_subkeys);
130         printf("Number of values: %d\n", num_values);
131
132         if (max_valnamelen > 0)
133                 printf("Maximum value name length: %d\n", max_valnamelen);
134
135         if (max_valbufsize > 0)
136                 printf("Maximum value data length: %d\n", max_valbufsize);
137
138         if (max_subkeynamelen > 0)
139                 printf("Maximum sub key name length: %d\n", max_subkeynamelen);
140
141         error = reg_get_sec_desc(ctx, ctx->current, &sec_desc);
142         if (!W_ERROR_IS_OK(error)) {
143                 printf("Error getting security descriptor: %s\n", win_errstr(error));
144                 return WERR_OK;
145         }
146         ndr_print_debug((ndr_print_fn_t)ndr_print_security_descriptor,
147                         "Security", sec_desc);
148         talloc_free(sec_desc);
149
150         return WERR_OK;
151 }
152
153 static WERROR cmd_predef(struct regshell_context *ctx, int argc, const char **argv)
154 {
155         struct registry_key *ret = NULL;
156         if (argc < 2) {
157                 fprintf(stderr, "Usage: predef predefined-key-name\n");
158         } else if (!ctx) {
159                 fprintf(stderr, "No full registry loaded, no predefined keys defined\n");
160         } else {
161                 WERROR error = reg_get_predefined_key_by_name(ctx->registry,
162                                                               argv[1], &ret);
163
164                 if (!W_ERROR_IS_OK(error)) {
165                         fprintf(stderr, "Error opening predefined key %s: %s\n",
166                                 argv[1], win_errstr(error));
167                         return error;
168                 }
169
170                 ctx->predef = strupper_talloc(ctx, argv[1]);
171                 ctx->current = ret;
172                 ctx->root = ret;
173         }
174
175         return WERR_OK;
176 }
177
178 static WERROR cmd_pwd(struct regshell_context *ctx,
179                       int argc, const char **argv)
180 {
181         if (ctx->predef) {
182                 printf("%s\\", ctx->predef);
183         }
184         printf("%s\n", ctx->path);
185         return WERR_OK;
186 }
187
188 static WERROR cmd_set(struct regshell_context *ctx, int argc, const char **argv)
189 {
190         struct registry_value val;
191         WERROR error;
192
193         if (argc < 4) {
194                 fprintf(stderr, "Usage: set value-name type value\n");
195                 return WERR_INVALID_PARAMETER;
196         }
197
198         if (!reg_string_to_val(ctx, argv[2], argv[3], &val.data_type, &val.data)) {
199                 fprintf(stderr, "Unable to interpret data\n");
200                 return WERR_INVALID_PARAMETER;
201         }
202
203         error = reg_val_set(ctx->current, argv[1], val.data_type, val.data);
204         if (!W_ERROR_IS_OK(error)) {
205                 fprintf(stderr, "Error setting value: %s\n", win_errstr(error));
206                 return error;
207         }
208
209         return WERR_OK;
210 }
211
212 static WERROR cmd_ck(struct regshell_context *ctx, int argc, const char **argv)
213 {
214         struct registry_key *nkey = NULL;
215         char *full_path;
216         WERROR error;
217
218         if(argc == 2) {
219                 if (!W_ERROR_IS_OK(get_full_path(ctx, argv[1], &full_path))) {
220                         fprintf(stderr, "Unable to parse the supplied path\n");
221                         return WERR_INVALID_PARAMETER;
222                 }
223                 error = reg_open_key(ctx->registry, ctx->root, full_path,
224                                      &nkey);
225                 if(!W_ERROR_IS_OK(error)) {
226                         DEBUG(0, ("Error opening specified key: %s\n",
227                                 win_errstr(error)));
228                         return error;
229                 }
230
231                 talloc_free(ctx->path);
232                 ctx->path = full_path;
233
234                 ctx->current = nkey;
235         }
236         printf("New path is: %s\\%s\n", ctx->predef?ctx->predef:"", ctx->path);
237
238         return WERR_OK;
239 }
240
241 static WERROR cmd_print(struct regshell_context *ctx, int argc, const char **argv)
242 {
243         uint32_t value_type;
244         DATA_BLOB value_data;
245         WERROR error;
246
247         if (argc != 2) {
248                 fprintf(stderr, "Usage: print <valuename>\n");
249                 return WERR_INVALID_PARAMETER;
250         }
251
252         error = reg_key_get_value_by_name(ctx, ctx->current, argv[1],
253                                           &value_type, &value_data);
254         if (!W_ERROR_IS_OK(error)) {
255                 fprintf(stderr, "No such value '%s'\n", argv[1]);
256                 return error;
257         }
258
259         printf("%s\n%s\n", str_regtype(value_type),
260                    reg_val_data_string(ctx, value_type, value_data));
261
262         return WERR_OK;
263 }
264
265 static WERROR cmd_ls(struct regshell_context *ctx, int argc, const char **argv)
266 {
267         unsigned int i;
268         WERROR error;
269         uint32_t valuetype;
270         DATA_BLOB valuedata;
271         const char *name = NULL;
272
273         for (i = 0; W_ERROR_IS_OK(error = reg_key_get_subkey_by_index(ctx,
274                                                                       ctx->current,
275                                                                       i,
276                                                                       &name,
277                                                                       NULL,
278                                                                       NULL)); i++) {
279                 printf("K %s\n", name);
280         }
281
282         if (!W_ERROR_EQUAL(error, WERR_NO_MORE_ITEMS)) {
283                 fprintf(stderr, "Error occurred while browsing through keys: %s\n",
284                         win_errstr(error));
285                 return error;
286         }
287
288         for (i = 0; W_ERROR_IS_OK(error = reg_key_get_value_by_index(ctx,
289                 ctx->current, i, &name, &valuetype, &valuedata)); i++)
290                 printf("V \"%s\" %s %s\n", name, str_regtype(valuetype),
291                            reg_val_data_string(ctx, valuetype, valuedata));
292
293         return WERR_OK;
294 }
295 static WERROR cmd_mkkey(struct regshell_context *ctx, int argc, const char **argv)
296 {
297         struct registry_key *tmp;
298         WERROR error;
299
300         if(argc < 2) {
301                 fprintf(stderr, "Usage: mkkey <keyname>\n");
302                 return WERR_INVALID_PARAMETER;
303         }
304
305         error = reg_key_add_name(ctx, ctx->current, argv[1], 0, NULL, &tmp);
306
307         if (!W_ERROR_IS_OK(error)) {
308                 fprintf(stderr, "Error adding new subkey '%s': %s\n", argv[1],
309                         win_errstr(error));
310                 return error;
311         }
312
313         return WERR_OK;
314 }
315
316 static WERROR cmd_rmkey(struct regshell_context *ctx,
317                         int argc, const char **argv)
318 {
319         WERROR error;
320
321         if(argc < 2) {
322                 fprintf(stderr, "Usage: rmkey <name>\n");
323                 return WERR_INVALID_PARAMETER;
324         }
325
326         error = reg_key_del(ctx, ctx->current, argv[1]);
327         if(!W_ERROR_IS_OK(error)) {
328                 fprintf(stderr, "Error deleting '%s'\n", argv[1]);
329                 return error;
330         } else {
331                 fprintf(stderr, "Successfully deleted '%s'\n", argv[1]);
332         }
333
334         return WERR_OK;
335 }
336
337 static WERROR cmd_rmval(struct regshell_context *ctx, int argc, const char **argv)
338 {
339         WERROR error;
340
341         if(argc < 2) {
342                 fprintf(stderr, "Usage: rmval <valuename>\n");
343                 return WERR_INVALID_PARAMETER;
344         }
345
346         error = reg_del_value(ctx, ctx->current, argv[1]);
347         if(!W_ERROR_IS_OK(error)) {
348                 fprintf(stderr, "Error deleting value '%s'\n", argv[1]);
349                 return error;
350         } else {
351                 fprintf(stderr, "Successfully deleted value '%s'\n", argv[1]);
352         }
353
354         return WERR_OK;
355 }
356
357 _NORETURN_ static WERROR cmd_exit(struct regshell_context *ctx,
358                                   int argc, const char **argv)
359 {
360         exit(0);
361 }
362
363 static WERROR cmd_help(struct regshell_context *ctx, int, const char **);
364
365 static struct {
366         const char *name;
367         const char *alias;
368         const char *help;
369         WERROR (*handle)(struct regshell_context *ctx, int argc, const char **argv);
370 } regshell_cmds[] = {
371         {"ck", "cd", "Change current key", cmd_ck },
372         {"info", "i", "Show detailed information of a key", cmd_info },
373         {"list", "ls", "List values/keys in current key", cmd_ls },
374         {"print", "p", "Print value", cmd_print },
375         {"mkkey", "mkdir", "Make new key", cmd_mkkey },
376         {"rmval", "rm", "Remove value", cmd_rmval },
377         {"rmkey", "rmdir", "Remove key", cmd_rmkey },
378         {"pwd", "pwk", "Printing current key", cmd_pwd },
379         {"set", "update", "Update value", cmd_set },
380         {"help", "?", "Help", cmd_help },
381         {"exit", "quit", "Exit", cmd_exit },
382         {"predef", "predefined", "Go to predefined key", cmd_predef },
383         {NULL }
384 };
385
386 static WERROR cmd_help(struct regshell_context *ctx,
387                        int argc, const char **argv)
388 {
389         unsigned int i;
390         printf("Available commands:\n");
391         for(i = 0; regshell_cmds[i].name; i++) {
392                 printf("%s - %s\n", regshell_cmds[i].name,
393                         regshell_cmds[i].help);
394         }
395         return WERR_OK;
396 }
397
398 static WERROR process_cmd(struct regshell_context *ctx,
399                           char *line)
400 {
401         int argc;
402         const char **argv = NULL;
403         int ret, i;
404
405         if ((ret = poptParseArgvString(line, &argc, &argv)) != 0) {
406                 fprintf(stderr, "regshell: %s\n", poptStrerror(ret));
407                 return WERR_INVALID_PARAMETER;
408         }
409
410         for(i = 0; regshell_cmds[i].name; i++) {
411                 if(!strcmp(regshell_cmds[i].name, argv[0]) ||
412                    (regshell_cmds[i].alias && !strcmp(regshell_cmds[i].alias, argv[0]))) {
413                         return regshell_cmds[i].handle(ctx, argc, argv);
414                 }
415         }
416
417         fprintf(stderr, "No such command '%s'\n", argv[0]);
418
419         return WERR_INVALID_PARAMETER;
420 }
421
422 #define MAX_COMPLETIONS 100
423
424 static struct registry_key *current_key = NULL;
425
426 static char **reg_complete_command(const char *text, int start, int end)
427 {
428         /* Complete command */
429         char **matches;
430         size_t len, samelen=0;
431         size_t i, count = 1;
432
433         matches = malloc_array_p(char *, MAX_COMPLETIONS);
434         if (!matches) return NULL;
435         matches[0] = NULL;
436
437         len = strlen(text);
438         for (i=0;regshell_cmds[i].handle && count < MAX_COMPLETIONS-1;i++) {
439                 if (strncmp(text, regshell_cmds[i].name, len) == 0) {
440                         matches[count] = strdup(regshell_cmds[i].name);
441                         if (!matches[count])
442                                 goto cleanup;
443                         if (count == 1)
444                                 samelen = strlen(matches[count]);
445                         else
446                                 while (strncmp(matches[count], matches[count-1], samelen) != 0)
447                                         samelen--;
448                         count++;
449                 }
450         }
451
452         switch (count) {
453         case 0: /* should never happen */
454         case 1:
455                 goto cleanup;
456         case 2:
457                 matches[0] = strdup(matches[1]);
458                 break;
459         default:
460                 matches[0] = strndup(matches[1], samelen);
461         }
462         matches[count] = NULL;
463         return matches;
464
465 cleanup:
466         for (i = 0; i < count; i++) {
467                 free(matches[i]);
468         }
469         free(matches);
470         return NULL;
471 }
472
473 static char **reg_complete_key(const char *text, int start, int end)
474 {
475         struct registry_key *base;
476         const char *subkeyname;
477         unsigned int i, j = 1;
478         size_t len, samelen = 0;
479         char **matches;
480         const char *base_n = "";
481         TALLOC_CTX *mem_ctx;
482         WERROR status;
483         int ret;
484
485         matches = malloc_array_p(char *, MAX_COMPLETIONS);
486         if (!matches) return NULL;
487         matches[0] = NULL;
488         mem_ctx = talloc_init("completion");
489
490         base = current_key;
491
492         len = strlen(text);
493         for(i = 0; j < MAX_COMPLETIONS-1; i++) {
494                 status = reg_key_get_subkey_by_index(mem_ctx, base, i,
495                                              &subkeyname, NULL, NULL);
496                 if(W_ERROR_IS_OK(status)) {
497                         if(!strncmp(text, subkeyname, len)) {
498                                 matches[j] = strdup(subkeyname);
499                                 j++;
500
501                                 if (j == 1)
502                                         samelen = strlen(matches[j]);
503                                 else
504                                         while (strncmp(matches[j], matches[j-1], samelen) != 0)
505                                                 samelen--;
506                         }
507                 } else if(W_ERROR_EQUAL(status, WERR_NO_MORE_ITEMS)) {
508                         break;
509                 } else {
510                         int n;
511
512                         printf("Error creating completion list: %s\n",
513                                 win_errstr(status));
514
515                         for (n = j; n >= 0; n--) {
516                                 SAFE_FREE(matches[n]);
517                         }
518                         SAFE_FREE(matches);
519                         talloc_free(mem_ctx);
520                         return NULL;
521                 }
522         }
523
524         if (j == 1) { /* No matches at all */
525                 SAFE_FREE(matches);
526                 talloc_free(mem_ctx);
527                 return NULL;
528         }
529
530         if (j == 2) { /* Exact match */
531                 ret = asprintf(&matches[0], "%s%s", base_n, matches[1]);
532         } else {
533                 ret = asprintf(&matches[0], "%s%s", base_n,
534                                 talloc_strndup(mem_ctx, matches[1], samelen));
535         }
536         talloc_free(mem_ctx);
537         if (ret == -1) {
538                 SAFE_FREE(matches);
539                 return NULL;
540         }
541
542         matches[j] = NULL;
543         return matches;
544 }
545
546 static char **reg_completion(const char *text, int start, int end)
547 {
548         smb_readline_ca_char(' ');
549
550         if (start == 0) {
551                 return reg_complete_command(text, start, end);
552         } else {
553                 return reg_complete_key(text, start, end);
554         }
555 }
556
557 int main(int argc, const char **argv)
558 {
559         int opt;
560         const char *file = NULL;
561         poptContext pc;
562         const char *remote = NULL;
563         struct regshell_context *ctx;
564         struct tevent_context *ev_ctx;
565         bool ret = true;
566         struct poptOption long_options[] = {
567                 POPT_AUTOHELP
568                 {"file", 'F', POPT_ARG_STRING, &file, 0, "open hive file", NULL },
569                 {"remote", 'R', POPT_ARG_STRING, &remote, 0, "connect to specified remote server", NULL},
570                 POPT_COMMON_SAMBA
571                 POPT_COMMON_CREDENTIALS
572                 POPT_COMMON_VERSION
573                 { NULL }
574         };
575
576         pc = poptGetContext(argv[0], argc, argv, long_options,0);
577
578         while((opt = poptGetNextOpt(pc)) != -1) {
579         }
580
581         ctx = talloc_zero(NULL, struct regshell_context);
582
583         ev_ctx = s4_event_context_init(ctx);
584
585         if (remote != NULL) {
586                 ctx->registry = reg_common_open_remote(remote, ev_ctx,
587                                          cmdline_lp_ctx,
588                                         popt_get_cmdline_credentials());
589         } else if (file != NULL) {
590                 ctx->current = reg_common_open_file(file, ev_ctx,
591                                         cmdline_lp_ctx,
592                                         popt_get_cmdline_credentials());
593                 if (ctx->current == NULL)
594                         return 1;
595                 ctx->registry = ctx->current->context;
596                 ctx->path = talloc_strdup(ctx, "");
597                 ctx->predef = NULL;
598                 ctx->root = ctx->current;
599         } else {
600                 ctx->registry = reg_common_open_local(
601                                         popt_get_cmdline_credentials(),
602                                         ev_ctx, cmdline_lp_ctx);
603         }
604
605         if (ctx->registry == NULL)
606                 return 1;
607
608         if (ctx->current == NULL) {
609                 unsigned int i;
610
611                 for (i = 0; (reg_predefined_keys[i].handle != 0) &&
612                         (ctx->current == NULL); i++) {
613                         WERROR err;
614                         err = reg_get_predefined_key(ctx->registry,
615                                                      reg_predefined_keys[i].handle,
616                                                      &ctx->current);
617                         if (W_ERROR_IS_OK(err)) {
618                                 ctx->predef = talloc_strdup(ctx,
619                                                           reg_predefined_keys[i].name);
620                                 ctx->path = talloc_strdup(ctx, "");
621                                 ctx->root = ctx->current;
622                                 break;
623                         } else {
624                                 ctx->current = NULL;
625                                 ctx->root = NULL;
626                         }
627                 }
628         }
629
630         if (ctx->current == NULL) {
631                 fprintf(stderr, "Unable to access any of the predefined keys\n");
632                 return 1;
633         }
634
635         poptFreeContext(pc);
636
637         while (true) {
638                 char *line, *prompt;
639
640                 if (asprintf(&prompt, "%s\\%s> ", ctx->predef?ctx->predef:"",
641                              ctx->path) < 0) {
642                         ret = false;
643                         break;
644                 }
645
646                 current_key = ctx->current;             /* No way to pass a void * pointer
647                                                            via readline :-( */
648                 line = smb_readline(prompt, NULL, reg_completion);
649
650                 if (line == NULL) {
651                         free(prompt);
652                         break;
653                 }
654
655                 if (line[0] != '\n') {
656                         ret = W_ERROR_IS_OK(process_cmd(ctx, line));
657                 }
658                 free(line);
659                 free(prompt);
660         }
661         talloc_free(ctx);
662
663         return (ret?0:1);
664 }