Use common popt definition for -d option.
[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
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.
11    
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.
16    
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.
20 */
21
22 #include "includes.h"
23 #include "rpcclient.h"
24
25 DOM_SID domain_sid;
26
27 /* List to hold groups of commands */
28
29 static struct cmd_list {
30         struct cmd_list *prev, *next;
31         struct cmd_set *cmd_set;
32 } *cmd_list;
33
34 /****************************************************************************
35 handle completion of commands for readline
36 ****************************************************************************/
37 static char **completion_fn(char *text, int start, int end)
38 {
39 #define MAX_COMPLETIONS 100
40         char **matches;
41         int i, count=0;
42         struct cmd_list *commands = cmd_list;
43
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
51
52         /* make sure we have a list of valid commands */
53         if (!commands) 
54                 return NULL;
55
56         matches = (char **)malloc(sizeof(matches[0])*MAX_COMPLETIONS);
57         if (!matches) return NULL;
58
59         matches[count++] = strdup(text);
60         if (!matches[0]) return NULL;
61
62         while (commands && count < MAX_COMPLETIONS-1) 
63         {
64                 if (!commands->cmd_set)
65                         break;
66                 
67                 for (i=0; commands->cmd_set[i].name; i++)
68                 {
69                         if ((strncmp(text, commands->cmd_set[i].name, strlen(text)) == 0) &&
70                                 commands->cmd_set[i].fn) 
71                         {
72                                 matches[count] = strdup(commands->cmd_set[i].name);
73                                 if (!matches[count]) 
74                                         return NULL;
75                                 count++;
76                         }
77                 }
78                 
79                 commands = commands->next;
80                 
81         }
82
83         if (count == 2) {
84                 SAFE_FREE(matches[0]);
85                 matches[0] = strdup(matches[1]);
86         }
87         matches[count] = NULL;
88         return matches;
89 }
90
91 /***********************************************************************
92  * read in username/password credentials from a file
93  */
94 static void read_authfile (
95         char *filename, 
96         char* username, 
97         char* password, 
98         char* domain
99 )
100 {
101         FILE *auth;
102         fstring buf;
103         uint16 len = 0;
104         char *ptr, *val, *param;
105                                
106         if ((auth=sys_fopen(filename, "r")) == NULL)
107         {
108                 printf ("ERROR: Unable to open credentials file!\n");
109                 return;
110         }
111                                 
112         while (!feof(auth))
113         {  
114                 /* get a line from the file */
115                 if (!fgets (buf, sizeof(buf), auth))
116                         continue;
117                 
118                 len = strlen(buf);
119                 
120                 /* skip empty lines */                  
121                 if ((len) && (buf[len-1]=='\n'))
122                 {
123                         buf[len-1] = '\0';
124                         len--;
125                 }       
126                 if (len == 0)
127                         continue;
128                                         
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';
136                                         
137                 /* eat leading white space */
138                 while ((*val!='\0') && ((*val==' ') || (*val=='\t')))
139                         val++;
140                                         
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);
147                                                 
148                 memset(buf, 0, sizeof(buf));
149         }
150         fclose(auth);
151         
152         return;
153 }
154
155 static char* next_command (char** cmdstr)
156 {
157         static pstring          command;
158         char                    *p;
159         
160         if (!cmdstr || !(*cmdstr))
161                 return NULL;
162         
163         p = strchr_m(*cmdstr, ';');
164         if (p)
165                 *p = '\0';
166         pstrcpy(command, *cmdstr);
167         *cmdstr = p;
168         
169         return command;
170 }
171
172 static void get_username (char *username)
173 {
174         if (getenv("USER"))
175                 pstrcpy(username,getenv("USER"));
176  
177         if (*username == 0 && getenv("LOGNAME"))
178                 pstrcpy(username,getenv("LOGNAME"));
179  
180         if (*username == 0) {
181                 pstrcpy(username,"GUEST");
182         }
183
184         return;
185 }
186
187 /* Fetch the SID for this computer */
188
189 static void fetch_machine_sid(struct cli_state *cli)
190 {
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;
197
198         if (got_domain_sid) return;
199
200         if (!(mem_ctx=talloc_init()))
201         {
202                 DEBUG(0,("fetch_machine_sid: talloc_init returned NULL!\n"));
203                 goto error;
204         }
205
206
207         if (!cli_nt_session_open (cli, PIPE_LSARPC)) {
208                 fprintf(stderr, "could not initialise lsa pipe\n");
209                 goto error;
210         }
211         
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;
217         }
218
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;
223         }
224
225         got_domain_sid = True;
226
227         cli_lsa_close(cli, mem_ctx, &pol);
228         cli_nt_session_close(cli);
229         talloc_destroy(mem_ctx);
230
231         return;
232
233  error:
234         fprintf(stderr, "could not obtain sid for domain %s\n", cli->domain);
235
236         if (!NT_STATUS_IS_OK(result)) {
237                 fprintf(stderr, "error: %s\n", nt_errstr(result));
238         }
239
240         exit(1);
241 }
242
243 /* List the available commands on a given pipe */
244
245 static NTSTATUS cmd_listcommands(struct cli_state *cli, TALLOC_CTX *mem_ctx,
246                          int argc, char **argv)
247 {
248         struct cmd_list *tmp;
249         struct cmd_set *tmp_set;
250         int i;
251
252         /* Usage */
253
254         if (argc != 2) {
255                 printf("Usage: %s <pipe>\n", argv[0]);
256                 return NT_STATUS_OK;
257         }
258
259         /* Help on one command */
260
261         for (tmp = cmd_list; tmp; tmp = tmp->next) 
262         {
263                 tmp_set = tmp->cmd_set;
264                 
265                 if (!StrCaseCmp(argv[1], tmp_set->name))
266                 {
267                         printf("Available commands on the %s pipe:\n\n", tmp_set->name);
268
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");
277                         }
278                         
279                         /* drop out of the loop */
280                         break;
281                 }
282         }
283         printf("\n\n");
284
285         return NT_STATUS_OK;
286 }
287
288 /* Display help on commands */
289
290 static NTSTATUS cmd_help(struct cli_state *cli, TALLOC_CTX *mem_ctx,
291                          int argc, char **argv)
292 {
293         struct cmd_list *tmp;
294         struct cmd_set *tmp_set;
295
296         /* Usage */
297
298         if (argc > 2) {
299                 printf("Usage: %s [command]\n", argv[0]);
300                 return NT_STATUS_OK;
301         }
302
303         /* Help on one command */
304
305         if (argc == 2) {
306                 for (tmp = cmd_list; tmp; tmp = tmp->next) {
307                         
308                         tmp_set = tmp->cmd_set;
309
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);
317
318                                         return NT_STATUS_OK;
319                                 }
320
321                                 tmp_set++;
322                         }
323                 }
324
325                 printf("No such command: %s\n", argv[1]);
326                 return NT_STATUS_OK;
327         }
328
329         /* List all commands */
330
331         for (tmp = cmd_list; tmp; tmp = tmp->next) {
332
333                 tmp_set = tmp->cmd_set;
334
335                 while(tmp_set->name) {
336
337                         printf("%15s\t\t%s\n", tmp_set->name,
338                                tmp_set->description ? tmp_set->description:
339                                "");
340
341                         tmp_set++;
342                 }
343         }
344
345         return NT_STATUS_OK;
346 }
347
348 /* Change the debug level */
349
350 static NTSTATUS cmd_debuglevel(struct cli_state *cli, TALLOC_CTX *mem_ctx,
351                                int argc, char **argv)
352 {
353         if (argc > 2) {
354                 printf("Usage: %s [debuglevel]\n", argv[0]);
355                 return NT_STATUS_OK;
356         }
357
358         if (argc == 2) {
359                 DEBUGLEVEL = atoi(argv[1]);
360         }
361
362         printf("debuglevel is %d\n", DEBUGLEVEL);
363
364         return NT_STATUS_OK;
365 }
366
367 static NTSTATUS cmd_quit(struct cli_state *cli, TALLOC_CTX *mem_ctx,
368                          int argc, char **argv)
369 {
370         exit(0);
371         return NT_STATUS_OK; /* NOTREACHED */
372 }
373
374 /* Build in rpcclient commands */
375
376 static struct cmd_set rpcclient_commands[] = {
377
378         { "GENERAL OPTIONS" },
379
380         { "help",       cmd_help,       NULL,   "Get help on commands", "[command]" },
381         { "?",          cmd_help,       NULL,   "Get help on commands", "[command]" },
382         { "debuglevel", cmd_debuglevel, NULL,   "Set debug level", "level" },
383         { "list",       cmd_listcommands, NULL, "List available commands on <pipe>", "pipe" },
384         { "exit",       cmd_quit,       NULL,   "Exit program", "" },
385         { "quit",       cmd_quit,       NULL,   "Exit program", "" },
386
387         { NULL }
388 };
389
390 static struct cmd_set separator_command[] = {
391         { "---------------", NULL,      NULL,   "----------------------" },
392         { NULL }
393 };
394
395
396 /* Various pipe commands */
397
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
406 static struct cmd_set *rpcclient_command_list[] = {
407         rpcclient_commands,
408         lsarpc_commands,
409         samr_commands,
410         spoolss_commands,
411         netlogon_commands,
412         srvsvc_commands,
413         dfs_commands,
414         reg_commands,
415         NULL
416 };
417
418 static void add_command_set(struct cmd_set *cmd_set)
419 {
420         struct cmd_list *entry;
421
422         if (!(entry = (struct cmd_list *)malloc(sizeof(struct cmd_list)))) {
423                 DEBUG(0, ("out of memory\n"));
424                 return;
425         }
426
427         ZERO_STRUCTP(entry);
428
429         entry->cmd_set = cmd_set;
430         DLIST_ADD(cmd_list, entry);
431 }
432
433 static NTSTATUS do_cmd(struct cli_state *cli, struct cmd_set *cmd_entry, 
434                        char *cmd)
435 {
436         char *p = cmd, **argv = NULL;
437         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
438         pstring buf;
439         int argc = 0, i;
440
441         /* Count number of arguments first time through the loop then
442            allocate memory and strdup them. */
443
444  again:
445         while(next_token(&p, buf, " ", sizeof(buf))) {
446                 if (argv) {
447                         argv[argc] = strdup(buf);
448                 }
449                 
450                 argc++;
451         }
452                                 
453         if (!argv) {
454
455                 /* Create argument list */
456
457                 argv = (char **)malloc(sizeof(char *) * argc);
458                 memset(argv, 0, sizeof(char *) * argc);
459
460                 if (!argv) {
461                         fprintf(stderr, "out of memory\n");
462                         result = NT_STATUS_NO_MEMORY;
463                         goto done;
464                 }
465                                         
466                 p = cmd;
467                 argc = 0;
468                                         
469                 goto again;
470         }
471
472         /* Call the function */
473
474         if (cmd_entry->fn) {
475                 TALLOC_CTX *mem_ctx;
476
477                 /* Create mem_ctx */
478
479                 if (!(mem_ctx = talloc_init())) {
480                         DEBUG(0, ("talloc_init() failed\n"));
481                         goto done;
482                 }
483
484                 /* Open pipe */
485
486                 if (cmd_entry->pipe)
487                         if (!cli_nt_session_open(cli, cmd_entry->pipe)) {
488                                 DEBUG(0, ("Could not initialise %s\n",
489                                           cmd_entry->pipe));
490                                 goto done;
491                         }
492
493                 /* Run command */
494
495                 result = cmd_entry->fn(cli, mem_ctx, argc, argv);
496
497                 /* Cleanup */
498
499                 if (cmd_entry->pipe)
500                         cli_nt_session_close(cli);
501
502                 talloc_destroy(mem_ctx);
503
504         } else {
505                 fprintf (stderr, "Invalid command\n");
506                 goto done;
507         }
508
509  done:
510                                                 
511         /* Cleanup */
512
513         if (argv) {
514                 for (i = 0; i < argc; i++)
515                         SAFE_FREE(argv[i]);
516         
517                 SAFE_FREE(argv);
518         }
519         
520         return result;
521 }
522
523 /* Process a command entered at the prompt or as part of -c */
524
525 static NTSTATUS process_cmd(struct cli_state *cli, char *cmd)
526 {
527         struct cmd_list *temp_list;
528         BOOL found = False;
529         pstring buf;
530         char *p = cmd;
531         NTSTATUS result = NT_STATUS_OK;
532         int len = 0;
533
534         if (cmd[strlen(cmd) - 1] == '\n')
535                 cmd[strlen(cmd) - 1] = '\0';
536
537         if (!next_token(&p, buf, " ", sizeof(buf))) {
538                 return NT_STATUS_OK;
539         }
540
541         /* strip the trainly \n if it exsists */
542         len = strlen(buf);
543         if (buf[len-1] == '\n')
544                 buf[len-1] = '\0';
545
546         /* Search for matching commands */
547
548         for (temp_list = cmd_list; temp_list; temp_list = temp_list->next) {
549                 struct cmd_set *temp_set = temp_list->cmd_set;
550
551                 while(temp_set->name) {
552                         if (strequal(buf, temp_set->name)) {
553                                 found = True;
554                                 result = do_cmd(cli, temp_set, cmd);
555
556                                 goto done;
557                         }
558                         temp_set++;
559                 }
560         }
561
562  done:
563         if (!found && buf[0]) {
564                 printf("command not found: %s\n", buf);
565                 return NT_STATUS_OK;
566         }
567
568         if (!NT_STATUS_IS_OK(result)) {
569                 printf("result was %s\n", nt_errstr(result));
570         }
571
572         return result;
573 }
574
575
576 /* Print usage information */
577 static void usage(void)
578 {
579         printf("Usage: rpcclient [options] server\n");
580
581         printf("\t-A or --authfile authfile          File containing user credentials\n");
582         printf("\t-c or --command \"command string\"   Execute semicolon separated cmds\n");
583         printf("\t-d or --debug debuglevel           Set the debuglevel\n");
584         printf("\t-l or --logfile logfile            Logfile to use instead of stdout\n");
585         printf("\t-h or --help                       Print this help message.\n");
586         printf("\t-N or --nopass                     Don't ask for a password\n");
587         printf("\t-s or --conf configfile            Specify an alternative config file\n");
588         printf("\t-U or --user username              Set the network username\n");
589         printf("\t-W or --workgroup domain           Set the domain name for user account\n");
590         printf("\t-I or --dest-ip ip                 Specify destination IP address\n");
591         printf("\n");
592 }
593
594 /* Main function */
595
596  int main(int argc, char *argv[])
597 {
598         extern pstring          global_myname;
599         static int              got_pass = 0;
600         BOOL                    interactive = True;
601         int                     opt;
602         int                     olddebug;
603         static char             *cmdstr = "";
604         const char *server;
605         struct cli_state        *cli;
606         fstring                 password="",
607                                 username="",
608                 domain="";
609         static char             *opt_authfile=NULL,
610                                 *opt_username=NULL,
611                                 *opt_domain=NULL,
612                                 *opt_configfile=NULL,
613                                 *opt_logfile=NULL,
614                                 *opt_ipaddr=NULL;
615         pstring                 logfile;
616         struct cmd_set          **cmd_set;
617         struct in_addr          server_ip;
618         NTSTATUS                nt_status;
619         extern BOOL             AllowDebugChange;
620
621         /* make sure the vars that get altered (4th field) are in
622            a fixed location or certain compilers complain */
623         poptContext pc;
624         struct poptOption long_options[] = {
625                 {"authfile",    'A', POPT_ARG_STRING,   &opt_authfile, 'A'},
626                 {"conf",        's', POPT_ARG_STRING,   &opt_configfile, 's'},
627                 {"nopass",      'N', POPT_ARG_NONE,     &got_pass},
628                 {"user",        'U', POPT_ARG_STRING,   &opt_username, 'U'},
629                 {"workgroup",   'W', POPT_ARG_STRING,   &opt_domain, 'W'},
630                 {"command",     'c', POPT_ARG_STRING,   &cmdstr},
631                 {"logfile",     'l', POPT_ARG_STRING,   &opt_logfile, 'l'},
632                 {"help",        'h', POPT_ARG_NONE,     0, 'h'},
633                 {"dest-ip",     'I', POPT_ARG_STRING,   &opt_ipaddr, 'I'},
634                 { NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_debug },
635                 { NULL }
636         };
637
638
639         setlinebuf(stdout);
640
641         DEBUGLEVEL = 1;
642         AllowDebugChange = False;
643
644         /* Parse options */
645
646         if (argc == 1) {
647                 usage();
648                 return 0;
649         }
650         
651         pc = poptGetContext("rpcclient", argc, (const char **) argv,
652                             long_options, 0);
653         
654         while((opt = poptGetNextOpt(pc)) != -1) {
655                 switch (opt) {
656                 case 'A':
657                         /* only get the username, password, and domain from the file */
658                         read_authfile (opt_authfile, username, password, domain);
659                         if (strlen (password))
660                                 got_pass = 1;
661                         break;
662                         
663                 case 'l':
664                         slprintf(logfile, sizeof(logfile) - 1, "%s.client", 
665                                  opt_logfile);
666                         lp_set_logfile(logfile);
667                         interactive = False;
668                         break;
669                         
670                 case 's':
671                         pstrcpy(dyn_CONFIGFILE, opt_configfile);
672                         break;
673                         
674                 case 'U': {
675                         char *lp;
676
677                         pstrcpy(username,opt_username);
678
679                         if ((lp=strchr_m(username,'%'))) {
680                                 *lp = 0;
681                                 pstrcpy(password,lp+1);
682                                 got_pass = 1;
683                                 memset(strchr_m(opt_username,'%') + 1, 'X',
684                                        strlen(password));
685                         }
686                         break;
687                 }
688                 case 'I':
689                         if (!inet_aton(opt_ipaddr, &server_ip)) {
690                                 fprintf(stderr, "%s not a valid IP address\n",
691                                         opt_ipaddr);
692                                 return 1;
693                         }
694                 case 'W':
695                         pstrcpy(domain, opt_domain);
696                         break;
697                         
698                 case 'h':
699                 default:
700                         usage();
701                         exit(1);
702                 }
703         }
704
705         /* Get server as remaining unparsed argument.  Print usage if more
706            than one unparsed argument is present. */
707
708         server = poptGetArg(pc);
709         
710         if (!server || poptGetArg(pc)) {
711                 usage();
712                 return 1;
713         }
714
715         poptFreeContext(pc);
716
717         /* the following functions are part of the Samba debugging
718            facilities.  See lib/debug.c */
719         setup_logging("rpcclient", interactive);
720         if (!interactive) 
721                 reopen_logs();
722         
723         /* Load smb.conf file */
724         /* FIXME!  How to get this DEBUGLEVEL to last over lp_load()? */
725         olddebug = DEBUGLEVEL;
726         if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
727                 fprintf(stderr, "Can't load %s\n", dyn_CONFIGFILE);
728         }
729         DEBUGLEVEL = olddebug;
730
731         load_interfaces();
732
733         get_myname((*global_myname)?NULL:global_myname);
734         strupper(global_myname);
735
736         /* Resolve the IP address */
737
738         if (!opt_ipaddr && !resolve_name(server, &server_ip, 0x20))  {
739                 DEBUG(1,("Unable to resolve %s\n", server));
740                 return 1;
741         }
742         
743         /*
744          * Get password
745          * from stdin if necessary
746          */
747
748         if (!got_pass) {
749                 char *pass = getpass("Password:");
750                 if (pass) {
751                         fstrcpy(password, pass);
752                 }
753         }
754         
755         if (!strlen(username) && !got_pass)
756                 get_username(username);
757                 
758         nt_status = cli_full_connection(&cli, global_myname, server, 
759                                         &server_ip, 0,
760                                         "IPC$", "IPC",  
761                                         username, domain,
762                                         password, 0);
763         
764         if (!NT_STATUS_IS_OK(nt_status)) {
765                 DEBUG(0,("Cannot connect to server.  Error was %s\n", nt_errstr(nt_status)));
766                 return 1;
767         }
768
769         memset(password,'X',sizeof(password));
770
771         /* Load command lists */
772
773         cmd_set = rpcclient_command_list;
774
775         while(*cmd_set) {
776                 add_command_set(*cmd_set);
777                 add_command_set(separator_command);
778                 cmd_set++;
779         }
780
781         fetch_machine_sid(cli);
782  
783        /* Do anything specified with -c */
784         if (cmdstr[0]) {
785                 char    *cmd;
786                 char    *p = cmdstr;
787  
788                 while((cmd=next_command(&p)) != NULL) {
789                         process_cmd(cli, cmd);
790                 }
791                 
792                 cli_shutdown(cli);
793                 return 0;
794         }
795
796         /* Loop around accepting commands */
797
798         while(1) {
799                 pstring prompt;
800                 char *line;
801
802                 slprintf(prompt, sizeof(prompt) - 1, "rpcclient $> ");
803
804                 line = smb_readline(prompt, NULL, completion_fn);
805
806                 if (line == NULL)
807                         break;
808
809                 if (line[0] != '\n')
810                         process_cmd(cli, line);
811         }
812         
813         cli_shutdown(cli);
814         return 0;
815 }