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