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