Patch from metze and me that adds dummy smb_register_*() functions
[gd/samba-autobuild/.git] / source3 / rpcclient / rpcclient.c
1 /* 
2    Unix SMB/CIFS implementation.
3    RPC pipe client
4
5    Copyright (C) Tim Potter 2000-2001
6    Copyright (C) Martin Pool 2003
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 2 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, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "rpcclient.h"
25
26
27 #define HAVE_SMB_REGISTER_PASSDB
28 #include "module_dummy.h"
29
30 DOM_SID domain_sid;
31
32
33 /* List to hold groups of commands.
34  *
35  * Commands are defined in a list of arrays: arrays are easy to
36  * statically declare, and lists are easier to dynamically extend.
37  */
38
39 static struct cmd_list {
40         struct cmd_list *prev, *next;
41         struct cmd_set *cmd_set;
42 } *cmd_list;
43
44 /****************************************************************************
45 handle completion of commands for readline
46 ****************************************************************************/
47 static char **completion_fn(char *text, int start, int end)
48 {
49 #define MAX_COMPLETIONS 100
50         char **matches;
51         int i, count=0;
52         struct cmd_list *commands = cmd_list;
53
54 #if 0   /* JERRY */
55         /* FIXME!!!  -- what to do when completing argument? */
56         /* for words not at the start of the line fallback 
57            to filename completion */
58         if (start) 
59                 return NULL;
60 #endif
61
62         /* make sure we have a list of valid commands */
63         if (!commands) 
64                 return NULL;
65
66         matches = (char **)malloc(sizeof(matches[0])*MAX_COMPLETIONS);
67         if (!matches) return NULL;
68
69         matches[count++] = strdup(text);
70         if (!matches[0]) return NULL;
71
72         while (commands && count < MAX_COMPLETIONS-1) 
73         {
74                 if (!commands->cmd_set)
75                         break;
76                 
77                 for (i=0; commands->cmd_set[i].name; i++)
78                 {
79                         if ((strncmp(text, commands->cmd_set[i].name, strlen(text)) == 0) &&
80                                 (( commands->cmd_set[i].returntype == RPC_RTYPE_NTSTATUS &&
81                         commands->cmd_set[i].ntfn ) || 
82                       ( commands->cmd_set[i].returntype == RPC_RTYPE_WERROR &&
83                         commands->cmd_set[i].wfn)))
84                         {
85                                 matches[count] = strdup(commands->cmd_set[i].name);
86                                 if (!matches[count]) 
87                                         return NULL;
88                                 count++;
89                         }
90                 }
91                 
92                 commands = commands->next;
93                 
94         }
95
96         if (count == 2) {
97                 SAFE_FREE(matches[0]);
98                 matches[0] = strdup(matches[1]);
99         }
100         matches[count] = NULL;
101         return matches;
102 }
103
104 static char* next_command (char** cmdstr)
105 {
106         static pstring          command;
107         char                    *p;
108         
109         if (!cmdstr || !(*cmdstr))
110                 return NULL;
111         
112         p = strchr_m(*cmdstr, ';');
113         if (p)
114                 *p = '\0';
115         pstrcpy(command, *cmdstr);
116         if (p)
117                 *cmdstr = p + 1;
118         else
119                 *cmdstr = NULL;
120         
121         return command;
122 }
123
124 /* Fetch the SID for this computer */
125
126 static void fetch_machine_sid(struct cli_state *cli)
127 {
128         POLICY_HND pol;
129         NTSTATUS result = NT_STATUS_OK;
130         uint32 info_class = 5;
131         fstring domain_name;
132         static BOOL got_domain_sid;
133         TALLOC_CTX *mem_ctx;
134
135         if (got_domain_sid) return;
136
137         if (!(mem_ctx=talloc_init("fetch_machine_sid")))
138         {
139                 DEBUG(0,("fetch_machine_sid: talloc_init returned NULL!\n"));
140                 goto error;
141         }
142
143
144         if (!cli_nt_session_open (cli, PI_LSARPC)) {
145                 fprintf(stderr, "could not initialise lsa pipe\n");
146                 goto error;
147         }
148         
149         result = cli_lsa_open_policy(cli, mem_ctx, True, 
150                                      SEC_RIGHTS_MAXIMUM_ALLOWED,
151                                      &pol);
152         if (!NT_STATUS_IS_OK(result)) {
153                 goto error;
154         }
155
156         result = cli_lsa_query_info_policy(cli, mem_ctx, &pol, info_class, 
157                                            domain_name, &domain_sid);
158         if (!NT_STATUS_IS_OK(result)) {
159                 goto error;
160         }
161
162         got_domain_sid = True;
163
164         cli_lsa_close(cli, mem_ctx, &pol);
165         cli_nt_session_close(cli);
166         talloc_destroy(mem_ctx);
167
168         return;
169
170  error:
171         fprintf(stderr, "could not obtain sid for domain %s\n", cli->domain);
172
173         if (!NT_STATUS_IS_OK(result)) {
174                 fprintf(stderr, "error: %s\n", nt_errstr(result));
175         }
176
177         exit(1);
178 }
179
180 /* List the available commands on a given pipe */
181
182 static NTSTATUS cmd_listcommands(struct cli_state *cli, TALLOC_CTX *mem_ctx,
183                                  int argc, const char **argv)
184 {
185         struct cmd_list *tmp;
186         struct cmd_set *tmp_set;
187         int i;
188
189         /* Usage */
190
191         if (argc != 2) {
192                 printf("Usage: %s <pipe>\n", argv[0]);
193                 return NT_STATUS_OK;
194         }
195
196         /* Help on one command */
197
198         for (tmp = cmd_list; tmp; tmp = tmp->next) 
199         {
200                 tmp_set = tmp->cmd_set;
201                 
202                 if (!StrCaseCmp(argv[1], tmp_set->name))
203                 {
204                         printf("Available commands on the %s pipe:\n\n", tmp_set->name);
205
206                         i = 0;
207                         tmp_set++;
208                         while(tmp_set->name) {
209                                 printf("%20s", tmp_set->name);
210                                 tmp_set++;
211                                 i++;
212                                 if (i%4 == 0)
213                                         printf("\n");
214                         }
215                         
216                         /* drop out of the loop */
217                         break;
218                 }
219         }
220         printf("\n\n");
221
222         return NT_STATUS_OK;
223 }
224
225 /* Display help on commands */
226
227 static NTSTATUS cmd_help(struct cli_state *cli, TALLOC_CTX *mem_ctx,
228                          int argc, const char **argv)
229 {
230         struct cmd_list *tmp;
231         struct cmd_set *tmp_set;
232
233         /* Usage */
234
235         if (argc > 2) {
236                 printf("Usage: %s [command]\n", argv[0]);
237                 return NT_STATUS_OK;
238         }
239
240         /* Help on one command */
241
242         if (argc == 2) {
243                 for (tmp = cmd_list; tmp; tmp = tmp->next) {
244                         
245                         tmp_set = tmp->cmd_set;
246
247                         while(tmp_set->name) {
248                                 if (strequal(argv[1], tmp_set->name)) {
249                                         if (tmp_set->usage &&
250                                             tmp_set->usage[0])
251                                                 printf("%s\n", tmp_set->usage);
252                                         else
253                                                 printf("No help for %s\n", tmp_set->name);
254
255                                         return NT_STATUS_OK;
256                                 }
257
258                                 tmp_set++;
259                         }
260                 }
261
262                 printf("No such command: %s\n", argv[1]);
263                 return NT_STATUS_OK;
264         }
265
266         /* List all commands */
267
268         for (tmp = cmd_list; tmp; tmp = tmp->next) {
269
270                 tmp_set = tmp->cmd_set;
271
272                 while(tmp_set->name) {
273
274                         printf("%15s\t\t%s\n", tmp_set->name,
275                                tmp_set->description ? tmp_set->description:
276                                "");
277
278                         tmp_set++;
279                 }
280         }
281
282         return NT_STATUS_OK;
283 }
284
285 /* Change the debug level */
286
287 static NTSTATUS cmd_debuglevel(struct cli_state *cli, TALLOC_CTX *mem_ctx,
288                                int argc, const char **argv)
289 {
290         if (argc > 2) {
291                 printf("Usage: %s [debuglevel]\n", argv[0]);
292                 return NT_STATUS_OK;
293         }
294
295         if (argc == 2) {
296                 DEBUGLEVEL = atoi(argv[1]);
297         }
298
299         printf("debuglevel is %d\n", DEBUGLEVEL);
300
301         return NT_STATUS_OK;
302 }
303
304 static NTSTATUS cmd_quit(struct cli_state *cli, TALLOC_CTX *mem_ctx,
305                          int argc, const char **argv)
306 {
307         exit(0);
308         return NT_STATUS_OK; /* NOTREACHED */
309 }
310
311 /* Built in rpcclient commands */
312
313 static struct cmd_set rpcclient_commands[] = {
314
315         { "GENERAL OPTIONS" },
316
317         { "help", RPC_RTYPE_NTSTATUS, cmd_help, NULL,     -1,   "Get help on commands", "[command]" },
318         { "?",  RPC_RTYPE_NTSTATUS, cmd_help, NULL,       -1,   "Get help on commands", "[command]" },
319         { "debuglevel", RPC_RTYPE_NTSTATUS, cmd_debuglevel, NULL,   -1, "Set debug level", "level" },
320         { "list",       RPC_RTYPE_NTSTATUS, cmd_listcommands, NULL, -1, "List available commands on <pipe>", "pipe" },
321         { "exit", RPC_RTYPE_NTSTATUS, cmd_quit, NULL,   -1,     "Exit program", "" },
322         { "quit", RPC_RTYPE_NTSTATUS, cmd_quit, NULL,     -1,   "Exit program", "" },
323
324         { NULL }
325 };
326
327 static struct cmd_set separator_command[] = {
328         { "---------------", MAX_RPC_RETURN_TYPE, NULL, NULL,   -1,     "----------------------" },
329         { NULL }
330 };
331
332
333 /* Various pipe commands */
334
335 extern struct cmd_set lsarpc_commands[];
336 extern struct cmd_set samr_commands[];
337 extern struct cmd_set spoolss_commands[];
338 extern struct cmd_set netlogon_commands[];
339 extern struct cmd_set srvsvc_commands[];
340 extern struct cmd_set dfs_commands[];
341 extern struct cmd_set reg_commands[];
342 extern struct cmd_set ds_commands[];
343 extern struct cmd_set echo_commands[];
344
345 static struct cmd_set *rpcclient_command_list[] = {
346         rpcclient_commands,
347         lsarpc_commands,
348         ds_commands,
349         samr_commands,
350         spoolss_commands,
351         netlogon_commands,
352         srvsvc_commands,
353         dfs_commands,
354         reg_commands,
355         echo_commands,
356         NULL
357 };
358
359 static void add_command_set(struct cmd_set *cmd_set)
360 {
361         struct cmd_list *entry;
362
363         if (!(entry = (struct cmd_list *)malloc(sizeof(struct cmd_list)))) {
364                 DEBUG(0, ("out of memory\n"));
365                 return;
366         }
367
368         ZERO_STRUCTP(entry);
369
370         entry->cmd_set = cmd_set;
371         DLIST_ADD(cmd_list, entry);
372 }
373
374
375 /**
376  * Call an rpcclient function, passing an argv array.
377  *
378  * @param cmd Command to run, as a single string.
379  **/
380 static NTSTATUS do_cmd(struct cli_state *cli,
381                        struct cmd_set *cmd_entry,
382                        int argc, char **argv)
383 {
384      NTSTATUS ntresult;
385      WERROR wresult;
386         
387         TALLOC_CTX *mem_ctx;
388
389         /* Create mem_ctx */
390
391         if (!(mem_ctx = talloc_init("do_cmd"))) {
392                 DEBUG(0, ("talloc_init() failed\n"));
393                 return NT_STATUS_UNSUCCESSFUL;
394         }
395
396         /* Open pipe */
397
398         if (cmd_entry->pipe_idx == PI_NETLOGON) {
399                 uchar trust_password[16];
400                 uint32 sec_channel_type;
401
402                 if (!secrets_fetch_trust_account_password(lp_workgroup(),
403                                                           trust_password,
404                                                           NULL, &sec_channel_type)) {
405                         return NT_STATUS_UNSUCCESSFUL;
406                 }
407
408                 if (!cli_nt_open_netlogon(cli, trust_password,
409                                           sec_channel_type)) {
410                         DEBUG(0, ("Could not initialise NETLOGON pipe\n"));
411                         return NT_STATUS_UNSUCCESSFUL;
412                 }
413         } else {
414                 if (cmd_entry->pipe_idx != -1) {
415                         if (!cli_nt_session_open(cli, cmd_entry->pipe_idx)) {
416                                 DEBUG(0, ("Could not initialise %s\n",
417                                           get_pipe_name_from_index(cmd_entry->pipe_idx)));
418                                 return NT_STATUS_UNSUCCESSFUL;
419                         }
420                 }
421         }
422
423      /* Run command */
424
425      if ( cmd_entry->returntype == RPC_RTYPE_NTSTATUS ) {
426           ntresult = cmd_entry->ntfn(cli, mem_ctx, argc, (const char **) argv);
427           if (!NT_STATUS_IS_OK(ntresult)) {
428               printf("result was %s\n", nt_errstr(ntresult));
429           }
430      } else {
431           wresult = cmd_entry->wfn( cli, mem_ctx, argc, (const char **) argv);
432           /* print out the DOS error */
433           if (!W_ERROR_IS_OK(wresult)) {
434                   printf( "result was %s\n", dos_errstr(wresult));
435           }
436           ntresult = W_ERROR_IS_OK(wresult)?NT_STATUS_OK:NT_STATUS_UNSUCCESSFUL;
437      }
438             
439
440         /* Cleanup */
441
442         if (cmd_entry->pipe_idx != -1)
443                 cli_nt_session_close(cli);
444
445         talloc_destroy(mem_ctx);
446
447         return ntresult;
448 }
449
450
451 /**
452  * Process a command entered at the prompt or as part of -c
453  *
454  * @returns The NTSTATUS from running the command.
455  **/
456 static NTSTATUS process_cmd(struct cli_state *cli, char *cmd)
457 {
458         struct cmd_list *temp_list;
459         NTSTATUS result = NT_STATUS_OK;
460         int ret;
461         int argc;
462         char **argv = NULL;
463
464         if ((ret = poptParseArgvString(cmd, &argc, (const char ***) &argv)) != 0) {
465                 fprintf(stderr, "rpcclient: %s\n", poptStrerror(ret));
466                 return NT_STATUS_UNSUCCESSFUL;
467         }
468
469
470         /* Walk through a dlist of arrays of commands. */
471         for (temp_list = cmd_list; temp_list; temp_list = temp_list->next) {
472                 struct cmd_set *temp_set = temp_list->cmd_set;
473
474                 while (temp_set->name) {
475                         if (strequal(argv[0], temp_set->name)) {
476                                 if (!(temp_set->returntype == RPC_RTYPE_NTSTATUS && temp_set->ntfn ) &&
477                          !(temp_set->returntype == RPC_RTYPE_WERROR && temp_set->wfn )) {
478                                         fprintf (stderr, "Invalid command\n");
479                                         goto out_free;
480                                 }
481
482                                 result = do_cmd(cli, temp_set, argc, argv);
483
484                                 goto out_free;
485                         }
486                         temp_set++;
487                 }
488         }
489
490         if (argv[0]) {
491                 printf("command not found: %s\n", argv[0]);
492         }
493
494 out_free:
495 /* moved to do_cmd()
496         if (!NT_STATUS_IS_OK(result)) {
497                 printf("result was %s\n", nt_errstr(result));
498         }
499 */
500
501         if (argv) {
502                 /* NOTE: popt allocates the whole argv, including the
503                  * strings, as a single block.  So a single free is
504                  * enough to release it -- we don't free the
505                  * individual strings.  rtfm. */
506                 free(argv);
507         }
508         
509         return result;
510 }
511
512
513 /* Main function */
514
515  int main(int argc, char *argv[])
516 {
517         BOOL                    interactive = True;
518         int                     opt;
519         static char             *cmdstr = NULL;
520         const char *server;
521         struct cli_state        *cli;
522         static char             *opt_ipaddr=NULL;
523         struct cmd_set          **cmd_set;
524         struct in_addr          server_ip;
525         NTSTATUS                nt_status;
526
527         /* make sure the vars that get altered (4th field) are in
528            a fixed location or certain compilers complain */
529         poptContext pc;
530         struct poptOption long_options[] = {
531                 POPT_AUTOHELP
532                 {"command",     'c', POPT_ARG_STRING,   &cmdstr, 'c', "Execute semicolon separated cmds", "COMMANDS"},
533                 {"dest-ip", 'I', POPT_ARG_STRING,   &opt_ipaddr, 'I', "Specify destination IP address", "IP"},
534                 POPT_COMMON_SAMBA
535                 POPT_COMMON_CONNECTION
536                 POPT_COMMON_CREDENTIALS
537                 POPT_TABLEEND
538         };
539
540         ZERO_STRUCT(server_ip);
541
542         setlinebuf(stdout);
543
544         /* the following functions are part of the Samba debugging
545            facilities.  See lib/debug.c */
546         setup_logging("rpcclient", interactive);
547         if (!interactive) 
548                 reopen_logs();
549         
550         /* Load smb.conf file */
551
552         if (!lp_load(dyn_CONFIGFILE,True,False,False))
553                 fprintf(stderr, "Can't load %s\n", dyn_CONFIGFILE);
554
555         /* Parse options */
556
557         pc = poptGetContext("rpcclient", argc, (const char **) argv,
558                             long_options, 0);
559
560         if (argc == 1) {
561                 poptPrintHelp(pc, stderr, 0);
562                 return 0;
563         }
564         
565         while((opt = poptGetNextOpt(pc)) != -1) {
566                 switch (opt) {
567
568                 case 'I':
569                         if ( (server_ip.s_addr=inet_addr(opt_ipaddr)) == INADDR_NONE ) {
570                                 fprintf(stderr, "%s not a valid IP address\n",
571                                         opt_ipaddr);
572                                 return 1;
573                         }
574                 }
575         }
576
577         /* Get server as remaining unparsed argument.  Print usage if more
578            than one unparsed argument is present. */
579
580         server = poptGetArg(pc);
581         
582         if (!server || poptGetArg(pc)) {
583                 poptPrintHelp(pc, stderr, 0);
584                 return 1;
585         }
586
587         poptFreeContext(pc);
588
589         load_interfaces();
590
591         if (!init_names())
592                 return 1;
593
594         /*
595          * Get password
596          * from stdin if necessary
597          */
598
599         if (!cmdline_auth_info.got_pass) {
600                 char *pass = getpass("Password:");
601                 if (pass) {
602                         pstrcpy(cmdline_auth_info.password, pass);
603                 }
604         }
605         
606         nt_status = cli_full_connection(&cli, global_myname(), server, 
607                                         opt_ipaddr ? &server_ip : NULL, 0,
608                                         "IPC$", "IPC",  
609                                         cmdline_auth_info.username, lp_workgroup(),
610                                         cmdline_auth_info.password, 0, NULL);
611         
612         if (!NT_STATUS_IS_OK(nt_status)) {
613                 DEBUG(0,("Cannot connect to server.  Error was %s\n", nt_errstr(nt_status)));
614                 return 1;
615         }
616
617         memset(cmdline_auth_info.password,'X',sizeof(cmdline_auth_info.password));
618
619         /* Load command lists */
620
621         cmd_set = rpcclient_command_list;
622
623         while(*cmd_set) {
624                 add_command_set(*cmd_set);
625                 add_command_set(separator_command);
626                 cmd_set++;
627         }
628
629         fetch_machine_sid(cli);
630  
631        /* Do anything specified with -c */
632         if (cmdstr && cmdstr[0]) {
633                 char    *cmd;
634                 char    *p = cmdstr;
635                 int result = 0;
636  
637                 while((cmd=next_command(&p)) != NULL) {
638                         NTSTATUS cmd_result = process_cmd(cli, cmd);
639                         result = NT_STATUS_IS_ERR(cmd_result);
640                 }
641                 
642                 cli_shutdown(cli);
643                 return result;
644         }
645
646         /* Loop around accepting commands */
647
648         while(1) {
649                 pstring prompt;
650                 char *line;
651
652                 slprintf(prompt, sizeof(prompt) - 1, "rpcclient $> ");
653
654                 line = smb_readline(prompt, NULL, completion_fn);
655
656                 if (line == NULL)
657                         break;
658
659                 if (line[0] != '\n')
660                         process_cmd(cli, line);
661         }
662         
663         cli_shutdown(cli);
664         return 0;
665 }