Commit just a little more infrastructure for HAVE_GETDIRENTRIES
[Samba/gebeck_regimport.git] / source3 / rpcclient / rpcclient.c
blob2609519dc487d7da91818632b1e62245f625d77f
1 /*
2 Unix SMB/CIFS implementation.
3 RPC pipe client
5 Copyright (C) Tim Potter 2000-2001
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #include "includes.h"
23 #include "rpcclient.h"
25 DOM_SID domain_sid;
27 /* List to hold groups of commands */
29 static struct cmd_list {
30 struct cmd_list *prev, *next;
31 struct cmd_set *cmd_set;
32 } *cmd_list;
34 /****************************************************************************
35 handle completion of commands for readline
36 ****************************************************************************/
37 static char **completion_fn(char *text, int start, int end)
39 #define MAX_COMPLETIONS 100
40 char **matches;
41 int i, count=0;
42 struct cmd_list *commands = cmd_list;
44 #if 0 /* JERRY */
45 /* FIXME!!! -- what to do when completing argument? */
46 /* for words not at the start of the line fallback
47 to filename completion */
48 if (start)
49 return NULL;
50 #endif
52 /* make sure we have a list of valid commands */
53 if (!commands)
54 return NULL;
56 matches = (char **)malloc(sizeof(matches[0])*MAX_COMPLETIONS);
57 if (!matches) return NULL;
59 matches[count++] = strdup(text);
60 if (!matches[0]) return NULL;
62 while (commands && count < MAX_COMPLETIONS-1)
64 if (!commands->cmd_set)
65 break;
67 for (i=0; commands->cmd_set[i].name; i++)
69 if ((strncmp(text, commands->cmd_set[i].name, strlen(text)) == 0) &&
70 commands->cmd_set[i].fn)
72 matches[count] = strdup(commands->cmd_set[i].name);
73 if (!matches[count])
74 return NULL;
75 count++;
79 commands = commands->next;
83 if (count == 2) {
84 SAFE_FREE(matches[0]);
85 matches[0] = strdup(matches[1]);
87 matches[count] = NULL;
88 return matches;
91 /***********************************************************************
92 * read in username/password credentials from a file
94 static void read_authfile (
95 char *filename,
96 char* username,
97 char* password,
98 char* domain
101 FILE *auth;
102 fstring buf;
103 uint16 len = 0;
104 char *ptr, *val, *param;
106 if ((auth=sys_fopen(filename, "r")) == NULL)
108 printf ("ERROR: Unable to open credentials file!\n");
109 return;
112 while (!feof(auth))
114 /* get a line from the file */
115 if (!fgets (buf, sizeof(buf), auth))
116 continue;
118 len = strlen(buf);
120 /* skip empty lines */
121 if ((len) && (buf[len-1]=='\n'))
123 buf[len-1] = '\0';
124 len--;
126 if (len == 0)
127 continue;
129 /* break up the line into parameter & value.
130 will need to eat a little whitespace possibly */
131 param = buf;
132 if (!(ptr = strchr_m(buf, '=')))
133 continue;
134 val = ptr+1;
135 *ptr = '\0';
137 /* eat leading white space */
138 while ((*val!='\0') && ((*val==' ') || (*val=='\t')))
139 val++;
141 if (strwicmp("password", param) == 0)
142 fstrcpy (password, val);
143 else if (strwicmp("username", param) == 0)
144 fstrcpy (username, val);
145 else if (strwicmp("domain", param) == 0)
146 fstrcpy (domain, val);
148 memset(buf, 0, sizeof(buf));
150 fclose(auth);
152 return;
155 static char* next_command (char** cmdstr)
157 static pstring command;
158 char *p;
160 if (!cmdstr || !(*cmdstr))
161 return NULL;
163 p = strchr_m(*cmdstr, ';');
164 if (p)
165 *p = '\0';
166 pstrcpy(command, *cmdstr);
167 *cmdstr = p;
169 return command;
172 static void get_username (char *username)
174 if (getenv("USER"))
175 pstrcpy(username,getenv("USER"));
177 if (*username == 0 && getenv("LOGNAME"))
178 pstrcpy(username,getenv("LOGNAME"));
180 if (*username == 0) {
181 pstrcpy(username,"GUEST");
184 return;
187 /* Fetch the SID for this computer */
189 static void fetch_machine_sid(struct cli_state *cli)
191 POLICY_HND pol;
192 NTSTATUS result = NT_STATUS_OK;
193 uint32 info_class = 5;
194 fstring domain_name;
195 static BOOL got_domain_sid;
196 TALLOC_CTX *mem_ctx;
198 if (got_domain_sid) return;
200 if (!(mem_ctx=talloc_init("fetch_machine_sid")))
202 DEBUG(0,("fetch_machine_sid: talloc_init returned NULL!\n"));
203 goto error;
207 if (!cli_nt_session_open (cli, PI_LSARPC)) {
208 fprintf(stderr, "could not initialise lsa pipe\n");
209 goto error;
212 result = cli_lsa_open_policy(cli, mem_ctx, True,
213 SEC_RIGHTS_MAXIMUM_ALLOWED,
214 &pol);
215 if (!NT_STATUS_IS_OK(result)) {
216 goto error;
219 result = cli_lsa_query_info_policy(cli, mem_ctx, &pol, info_class,
220 domain_name, &domain_sid);
221 if (!NT_STATUS_IS_OK(result)) {
222 goto error;
225 got_domain_sid = True;
227 cli_lsa_close(cli, mem_ctx, &pol);
228 cli_nt_session_close(cli);
229 talloc_destroy(mem_ctx);
231 return;
233 error:
234 fprintf(stderr, "could not obtain sid for domain %s\n", cli->domain);
236 if (!NT_STATUS_IS_OK(result)) {
237 fprintf(stderr, "error: %s\n", nt_errstr(result));
240 exit(1);
243 /* List the available commands on a given pipe */
245 static NTSTATUS cmd_listcommands(struct cli_state *cli, TALLOC_CTX *mem_ctx,
246 int argc, char **argv)
248 struct cmd_list *tmp;
249 struct cmd_set *tmp_set;
250 int i;
252 /* Usage */
254 if (argc != 2) {
255 printf("Usage: %s <pipe>\n", argv[0]);
256 return NT_STATUS_OK;
259 /* Help on one command */
261 for (tmp = cmd_list; tmp; tmp = tmp->next)
263 tmp_set = tmp->cmd_set;
265 if (!StrCaseCmp(argv[1], tmp_set->name))
267 printf("Available commands on the %s pipe:\n\n", tmp_set->name);
269 i = 0;
270 tmp_set++;
271 while(tmp_set->name) {
272 printf("%20s", tmp_set->name);
273 tmp_set++;
274 i++;
275 if (i%4 == 0)
276 printf("\n");
279 /* drop out of the loop */
280 break;
283 printf("\n\n");
285 return NT_STATUS_OK;
288 /* Display help on commands */
290 static NTSTATUS cmd_help(struct cli_state *cli, TALLOC_CTX *mem_ctx,
291 int argc, char **argv)
293 struct cmd_list *tmp;
294 struct cmd_set *tmp_set;
296 /* Usage */
298 if (argc > 2) {
299 printf("Usage: %s [command]\n", argv[0]);
300 return NT_STATUS_OK;
303 /* Help on one command */
305 if (argc == 2) {
306 for (tmp = cmd_list; tmp; tmp = tmp->next) {
308 tmp_set = tmp->cmd_set;
310 while(tmp_set->name) {
311 if (strequal(argv[1], tmp_set->name)) {
312 if (tmp_set->usage &&
313 tmp_set->usage[0])
314 printf("%s\n", tmp_set->usage);
315 else
316 printf("No help for %s\n", tmp_set->name);
318 return NT_STATUS_OK;
321 tmp_set++;
325 printf("No such command: %s\n", argv[1]);
326 return NT_STATUS_OK;
329 /* List all commands */
331 for (tmp = cmd_list; tmp; tmp = tmp->next) {
333 tmp_set = tmp->cmd_set;
335 while(tmp_set->name) {
337 printf("%15s\t\t%s\n", tmp_set->name,
338 tmp_set->description ? tmp_set->description:
339 "");
341 tmp_set++;
345 return NT_STATUS_OK;
348 /* Change the debug level */
350 static NTSTATUS cmd_debuglevel(struct cli_state *cli, TALLOC_CTX *mem_ctx,
351 int argc, char **argv)
353 if (argc > 2) {
354 printf("Usage: %s [debuglevel]\n", argv[0]);
355 return NT_STATUS_OK;
358 if (argc == 2) {
359 DEBUGLEVEL = atoi(argv[1]);
362 printf("debuglevel is %d\n", DEBUGLEVEL);
364 return NT_STATUS_OK;
367 static NTSTATUS cmd_quit(struct cli_state *cli, TALLOC_CTX *mem_ctx,
368 int argc, char **argv)
370 exit(0);
371 return NT_STATUS_OK; /* NOTREACHED */
374 /* Build in rpcclient commands */
376 static struct cmd_set rpcclient_commands[] = {
378 { "GENERAL OPTIONS" },
380 { "help", cmd_help, -1, "Get help on commands", "[command]" },
381 { "?", cmd_help, -1, "Get help on commands", "[command]" },
382 { "debuglevel", cmd_debuglevel, -1, "Set debug level", "level" },
383 { "list", cmd_listcommands, -1, "List available commands on <pipe>", "pipe" },
384 { "exit", cmd_quit, -1, "Exit program", "" },
385 { "quit", cmd_quit, -1, "Exit program", "" },
387 { NULL }
390 static struct cmd_set separator_command[] = {
391 { "---------------", NULL, -1, "----------------------" },
392 { NULL }
396 /* Various pipe commands */
398 extern struct cmd_set lsarpc_commands[];
399 extern struct cmd_set samr_commands[];
400 extern struct cmd_set spoolss_commands[];
401 extern struct cmd_set netlogon_commands[];
402 extern struct cmd_set srvsvc_commands[];
403 extern struct cmd_set dfs_commands[];
404 extern struct cmd_set reg_commands[];
405 extern struct cmd_set ds_commands[];
407 static struct cmd_set *rpcclient_command_list[] = {
408 rpcclient_commands,
409 lsarpc_commands,
410 ds_commands,
411 samr_commands,
412 spoolss_commands,
413 netlogon_commands,
414 srvsvc_commands,
415 dfs_commands,
416 reg_commands,
417 NULL
420 static void add_command_set(struct cmd_set *cmd_set)
422 struct cmd_list *entry;
424 if (!(entry = (struct cmd_list *)malloc(sizeof(struct cmd_list)))) {
425 DEBUG(0, ("out of memory\n"));
426 return;
429 ZERO_STRUCTP(entry);
431 entry->cmd_set = cmd_set;
432 DLIST_ADD(cmd_list, entry);
435 static NTSTATUS do_cmd(struct cli_state *cli, struct cmd_set *cmd_entry,
436 char *cmd)
438 char **argv = NULL;
439 const char *p = cmd;
440 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
441 pstring buf;
442 int argc = 0, i;
444 /* Count number of arguments first time through the loop then
445 allocate memory and strdup them. */
447 again:
448 while(next_token(&p, buf, " ", sizeof(buf))) {
449 if (argv) {
450 argv[argc] = strdup(buf);
453 argc++;
456 if (!argv) {
458 /* Create argument list */
460 argv = (char **)malloc(sizeof(char *) * argc);
461 memset(argv, 0, sizeof(char *) * argc);
463 if (!argv) {
464 fprintf(stderr, "out of memory\n");
465 result = NT_STATUS_NO_MEMORY;
466 goto done;
469 p = cmd;
470 argc = 0;
472 goto again;
475 /* Call the function */
477 if (cmd_entry->fn) {
478 TALLOC_CTX *mem_ctx;
480 /* Create mem_ctx */
482 if (!(mem_ctx = talloc_init("do_cmd"))) {
483 DEBUG(0, ("talloc_init() failed\n"));
484 goto done;
487 /* Open pipe */
489 if (cmd_entry->pipe_idx != -1)
490 if (!cli_nt_session_open(cli, cmd_entry->pipe_idx)) {
491 DEBUG(0, ("Could not initialise pipe\n"));
492 goto done;
495 /* Run command */
497 result = cmd_entry->fn(cli, mem_ctx, argc, argv);
499 /* Cleanup */
501 if (cmd_entry->pipe_idx != -1)
502 cli_nt_session_close(cli);
504 talloc_destroy(mem_ctx);
506 } else {
507 fprintf (stderr, "Invalid command\n");
508 goto done;
511 done:
513 /* Cleanup */
515 if (argv) {
516 for (i = 0; i < argc; i++)
517 SAFE_FREE(argv[i]);
519 SAFE_FREE(argv);
522 return result;
525 /* Process a command entered at the prompt or as part of -c */
527 static NTSTATUS process_cmd(struct cli_state *cli, char *cmd)
529 struct cmd_list *temp_list;
530 BOOL found = False;
531 pstring buf;
532 const char *p = cmd;
533 NTSTATUS result = NT_STATUS_OK;
534 int len = 0;
536 if (cmd[strlen(cmd) - 1] == '\n')
537 cmd[strlen(cmd) - 1] = '\0';
539 if (!next_token(&p, buf, " ", sizeof(buf))) {
540 return NT_STATUS_OK;
543 /* strip the trainly \n if it exsists */
544 len = strlen(buf);
545 if (buf[len-1] == '\n')
546 buf[len-1] = '\0';
548 /* Search for matching commands */
550 for (temp_list = cmd_list; temp_list; temp_list = temp_list->next) {
551 struct cmd_set *temp_set = temp_list->cmd_set;
553 while(temp_set->name) {
554 if (strequal(buf, temp_set->name)) {
555 found = True;
556 result = do_cmd(cli, temp_set, cmd);
558 goto done;
560 temp_set++;
564 done:
565 if (!found && buf[0]) {
566 printf("command not found: %s\n", buf);
567 return NT_STATUS_OK;
570 if (!NT_STATUS_IS_OK(result)) {
571 printf("result was %s\n", nt_errstr(result));
574 return result;
578 /* Main function */
580 int main(int argc, char *argv[])
582 static int got_pass = 0;
583 BOOL interactive = True;
584 int opt;
585 static char *cmdstr = "";
586 const char *server;
587 struct cli_state *cli;
588 fstring password="",
589 username="",
590 domain="";
591 static char *opt_authfile=NULL,
592 *opt_username=NULL,
593 *opt_domain=NULL,
594 *opt_logfile=NULL,
595 *opt_ipaddr=NULL;
596 pstring logfile;
597 struct cmd_set **cmd_set;
598 struct in_addr server_ip;
599 NTSTATUS nt_status;
601 /* make sure the vars that get altered (4th field) are in
602 a fixed location or certain compilers complain */
603 poptContext pc;
604 struct poptOption long_options[] = {
605 POPT_AUTOHELP
606 {"authfile", 'A', POPT_ARG_STRING, &opt_authfile, 'A', "File containing user credentials", "AUTHFILE"},
607 {"nopass", 'N', POPT_ARG_NONE, &got_pass, 'N', "Don't ask for a password"},
608 {"user", 'U', POPT_ARG_STRING, &opt_username, 'U', "Set the network username", "USER"},
609 {"workgroup", 'W', POPT_ARG_STRING, &opt_domain, 'W', "Set the domain name for user account", "DOMAIN"},
610 {"command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated cmds", "COMMANDS"},
611 {"logfile", 'l', POPT_ARG_STRING, &opt_logfile, 'l', "Logfile to use instead of stdout", "LOGFILE" },
612 {"dest-ip", 'I', POPT_ARG_STRING, &opt_ipaddr, 'I', "Specify destination IP address", "IP"},
613 { NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_debug },
614 { NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_configfile },
615 { NULL }
618 setlinebuf(stdout);
620 /* Parse options */
622 pc = poptGetContext("rpcclient", argc, (const char **) argv,
623 long_options, 0);
625 if (argc == 1) {
626 poptPrintHelp(pc, stderr, 0);
627 return 0;
630 while((opt = poptGetNextOpt(pc)) != -1) {
631 switch (opt) {
632 case 'A':
633 /* only get the username, password, and domain from the file */
634 read_authfile (opt_authfile, username, password, domain);
635 if (strlen (password))
636 got_pass = 1;
637 break;
639 case 'l':
640 slprintf(logfile, sizeof(logfile) - 1, "%s.client",
641 opt_logfile);
642 lp_set_logfile(logfile);
643 interactive = False;
644 break;
646 case 'U': {
647 char *lp;
649 fstrcpy(username,opt_username);
651 if ((lp=strchr_m(username,'%'))) {
652 *lp = 0;
653 fstrcpy(password,lp+1);
654 got_pass = 1;
655 memset(strchr_m(opt_username,'%') + 1, 'X',
656 strlen(password));
658 break;
660 case 'I':
661 if ( (server_ip.s_addr=inet_addr(opt_ipaddr)) == INADDR_NONE ) {
662 fprintf(stderr, "%s not a valid IP address\n",
663 opt_ipaddr);
664 return 1;
666 case 'W':
667 fstrcpy(domain, opt_domain);
668 break;
672 /* Get server as remaining unparsed argument. Print usage if more
673 than one unparsed argument is present. */
675 server = poptGetArg(pc);
677 if (!server || poptGetArg(pc)) {
678 poptPrintHelp(pc, stderr, 0);
679 return 1;
682 poptFreeContext(pc);
684 /* the following functions are part of the Samba debugging
685 facilities. See lib/debug.c */
686 setup_logging("rpcclient", interactive);
687 if (!interactive)
688 reopen_logs();
690 /* Load smb.conf file */
692 if (!lp_load(dyn_CONFIGFILE,True,False,False))
693 fprintf(stderr, "Can't load %s\n", dyn_CONFIGFILE);
695 load_interfaces();
697 if (!init_names())
698 return 1;
700 /* Resolve the IP address */
702 if (!opt_ipaddr && !resolve_name(server, &server_ip, 0x20)) {
703 fprintf(stderr, "Unable to resolve %s\n", server);
704 return 1;
708 * Get password
709 * from stdin if necessary
712 if (!got_pass) {
713 char *pass = getpass("Password:");
714 if (pass) {
715 fstrcpy(password, pass);
719 if (!strlen(username) && !got_pass)
720 get_username(username);
722 nt_status = cli_full_connection(&cli, global_myname(), server,
723 &server_ip, 0,
724 "IPC$", "IPC",
725 username, domain,
726 password, 0, NULL);
728 if (!NT_STATUS_IS_OK(nt_status)) {
729 DEBUG(0,("Cannot connect to server. Error was %s\n", nt_errstr(nt_status)));
730 return 1;
733 memset(password,'X',sizeof(password));
735 /* Load command lists */
737 cmd_set = rpcclient_command_list;
739 while(*cmd_set) {
740 add_command_set(*cmd_set);
741 add_command_set(separator_command);
742 cmd_set++;
745 fetch_machine_sid(cli);
747 /* Do anything specified with -c */
748 if (cmdstr[0]) {
749 char *cmd;
750 char *p = cmdstr;
752 while((cmd=next_command(&p)) != NULL) {
753 process_cmd(cli, cmd);
756 cli_shutdown(cli);
757 return 0;
760 /* Loop around accepting commands */
762 while(1) {
763 pstring prompt;
764 char *line;
766 slprintf(prompt, sizeof(prompt) - 1, "rpcclient $> ");
768 line = smb_readline(prompt, NULL, completion_fn);
770 if (line == NULL)
771 break;
773 if (line[0] != '\n')
774 process_cmd(cli, line);
777 cli_shutdown(cli);
778 return 0;