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