Merge branch 'v3-2-test' of ssh://git.samba.org/data/git/samba into v3-2-test
[kai/samba.git] / source3 / rpcclient / rpcclient.c
1 /* 
2    Unix SMB/CIFS implementation.
3    RPC pipe client
4
5    Copyright (C) Tim Potter 2000-2001
6    Copyright (C) Martin Pool 2003
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 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, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "rpcclient.h"
24
25 DOM_SID domain_sid;
26
27 static enum pipe_auth_type pipe_default_auth_type = PIPE_AUTH_TYPE_NONE;
28 static enum pipe_auth_level pipe_default_auth_level = PIPE_AUTH_LEVEL_NONE;
29 static unsigned int timeout = 0;
30
31 /* List to hold groups of commands.
32  *
33  * Commands are defined in a list of arrays: arrays are easy to
34  * statically declare, and lists are easier to dynamically extend.
35  */
36
37 static struct cmd_list {
38         struct cmd_list *prev, *next;
39         struct cmd_set *cmd_set;
40 } *cmd_list;
41
42 /****************************************************************************
43 handle completion of commands for readline
44 ****************************************************************************/
45 static char **completion_fn(const char *text, int start, int end)
46 {
47 #define MAX_COMPLETIONS 100
48         char **matches;
49         int i, count=0;
50         struct cmd_list *commands = cmd_list;
51
52 #if 0   /* JERRY */
53         /* FIXME!!!  -- what to do when completing argument? */
54         /* for words not at the start of the line fallback 
55            to filename completion */
56         if (start) 
57                 return NULL;
58 #endif
59
60         /* make sure we have a list of valid commands */
61         if (!commands) {
62                 return NULL;
63         }
64
65         matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
66         if (!matches) {
67                 return NULL;
68         }
69
70         matches[count++] = SMB_STRDUP(text);
71         if (!matches[0]) {
72                 SAFE_FREE(matches);
73                 return NULL;
74         }
75
76         while (commands && count < MAX_COMPLETIONS-1) {
77                 if (!commands->cmd_set) {
78                         break;
79                 }
80                 
81                 for (i=0; commands->cmd_set[i].name; i++) {
82                         if ((strncmp(text, commands->cmd_set[i].name, strlen(text)) == 0) &&
83                                 (( commands->cmd_set[i].returntype == RPC_RTYPE_NTSTATUS &&
84                         commands->cmd_set[i].ntfn ) || 
85                       ( commands->cmd_set[i].returntype == RPC_RTYPE_WERROR &&
86                         commands->cmd_set[i].wfn))) {
87                                 matches[count] = SMB_STRDUP(commands->cmd_set[i].name);
88                                 if (!matches[count]) {
89                                         for (i = 0; i < count; i++) {
90                                                 SAFE_FREE(matches[count]);
91                                         }
92                                         SAFE_FREE(matches);
93                                         return NULL;
94                                 }
95                                 count++;
96                         }
97                 }
98                 commands = commands->next;
99                 
100         }
101
102         if (count == 2) {
103                 SAFE_FREE(matches[0]);
104                 matches[0] = SMB_STRDUP(matches[1]);
105         }
106         matches[count] = NULL;
107         return matches;
108 }
109
110 static char *next_command (char **cmdstr)
111 {
112         char *command;
113         char                    *p;
114         
115         if (!cmdstr || !(*cmdstr))
116                 return NULL;
117         
118         p = strchr_m(*cmdstr, ';');
119         if (p)
120                 *p = '\0';
121         command = SMB_STRDUP(*cmdstr);
122         if (p)
123                 *cmdstr = p + 1;
124         else
125                 *cmdstr = NULL;
126         
127         return command;
128 }
129
130 /* Fetch the SID for this computer */
131
132 static void fetch_machine_sid(struct cli_state *cli)
133 {
134         POLICY_HND pol;
135         NTSTATUS result = NT_STATUS_OK;
136         static bool got_domain_sid;
137         TALLOC_CTX *mem_ctx;
138         struct rpc_pipe_client *lsapipe = NULL;
139         union lsa_PolicyInformation *info = NULL;
140
141         if (got_domain_sid) return;
142
143         if (!(mem_ctx=talloc_init("fetch_machine_sid"))) {
144                 DEBUG(0,("fetch_machine_sid: talloc_init returned NULL!\n"));
145                 goto error;
146         }
147
148         if ((lsapipe = cli_rpc_pipe_open_noauth(cli, PI_LSARPC, &result)) == NULL) {
149                 fprintf(stderr, "could not initialise lsa pipe. Error was %s\n", nt_errstr(result) );
150                 goto error;
151         }
152         
153         result = rpccli_lsa_open_policy(lsapipe, mem_ctx, True, 
154                                      SEC_RIGHTS_MAXIMUM_ALLOWED,
155                                      &pol);
156         if (!NT_STATUS_IS_OK(result)) {
157                 goto error;
158         }
159
160         result = rpccli_lsa_QueryInfoPolicy(lsapipe, mem_ctx,
161                                             &pol,
162                                             LSA_POLICY_INFO_ACCOUNT_DOMAIN,
163                                             &info);
164         if (!NT_STATUS_IS_OK(result)) {
165                 goto error;
166         }
167
168         got_domain_sid = True;
169         sid_copy(&domain_sid, info->account_domain.sid);
170
171         rpccli_lsa_Close(lsapipe, mem_ctx, &pol);
172         cli_rpc_pipe_close(lsapipe);
173         talloc_destroy(mem_ctx);
174
175         return;
176
177  error:
178
179         if (lsapipe) {
180                 cli_rpc_pipe_close(lsapipe);
181         }
182
183         fprintf(stderr, "could not obtain sid for domain %s\n", cli->domain);
184
185         if (!NT_STATUS_IS_OK(result)) {
186                 fprintf(stderr, "error: %s\n", nt_errstr(result));
187         }
188
189         exit(1);
190 }
191
192 /* List the available commands on a given pipe */
193
194 static NTSTATUS cmd_listcommands(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
195                                  int argc, const char **argv)
196 {
197         struct cmd_list *tmp;
198         struct cmd_set *tmp_set;
199         int i;
200
201         /* Usage */
202
203         if (argc != 2) {
204                 printf("Usage: %s <pipe>\n", argv[0]);
205                 return NT_STATUS_OK;
206         }
207
208         /* Help on one command */
209
210         for (tmp = cmd_list; tmp; tmp = tmp->next) 
211         {
212                 tmp_set = tmp->cmd_set;
213                 
214                 if (!StrCaseCmp(argv[1], tmp_set->name))
215                 {
216                         printf("Available commands on the %s pipe:\n\n", tmp_set->name);
217
218                         i = 0;
219                         tmp_set++;
220                         while(tmp_set->name) {
221                                 printf("%30s", tmp_set->name);
222                                 tmp_set++;
223                                 i++;
224                                 if (i%3 == 0)
225                                         printf("\n");
226                         }
227                         
228                         /* drop out of the loop */
229                         break;
230                 }
231         }
232         printf("\n\n");
233
234         return NT_STATUS_OK;
235 }
236
237 /* Display help on commands */
238
239 static NTSTATUS cmd_help(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
240                          int argc, const char **argv)
241 {
242         struct cmd_list *tmp;
243         struct cmd_set *tmp_set;
244
245         /* Usage */
246
247         if (argc > 2) {
248                 printf("Usage: %s [command]\n", argv[0]);
249                 return NT_STATUS_OK;
250         }
251
252         /* Help on one command */
253
254         if (argc == 2) {
255                 for (tmp = cmd_list; tmp; tmp = tmp->next) {
256                         
257                         tmp_set = tmp->cmd_set;
258
259                         while(tmp_set->name) {
260                                 if (strequal(argv[1], tmp_set->name)) {
261                                         if (tmp_set->usage &&
262                                             tmp_set->usage[0])
263                                                 printf("%s\n", tmp_set->usage);
264                                         else
265                                                 printf("No help for %s\n", tmp_set->name);
266
267                                         return NT_STATUS_OK;
268                                 }
269
270                                 tmp_set++;
271                         }
272                 }
273
274                 printf("No such command: %s\n", argv[1]);
275                 return NT_STATUS_OK;
276         }
277
278         /* List all commands */
279
280         for (tmp = cmd_list; tmp; tmp = tmp->next) {
281
282                 tmp_set = tmp->cmd_set;
283
284                 while(tmp_set->name) {
285
286                         printf("%15s\t\t%s\n", tmp_set->name,
287                                tmp_set->description ? tmp_set->description:
288                                "");
289
290                         tmp_set++;
291                 }
292         }
293
294         return NT_STATUS_OK;
295 }
296
297 /* Change the debug level */
298
299 static NTSTATUS cmd_debuglevel(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
300                                int argc, const char **argv)
301 {
302         if (argc > 2) {
303                 printf("Usage: %s [debuglevel]\n", argv[0]);
304                 return NT_STATUS_OK;
305         }
306
307         if (argc == 2) {
308                 DEBUGLEVEL = atoi(argv[1]);
309         }
310
311         printf("debuglevel is %d\n", DEBUGLEVEL);
312
313         return NT_STATUS_OK;
314 }
315
316 static NTSTATUS cmd_quit(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
317                          int argc, const char **argv)
318 {
319         exit(0);
320         return NT_STATUS_OK; /* NOTREACHED */
321 }
322
323 static NTSTATUS cmd_set_ss_level(void)
324 {
325         struct cmd_list *tmp;
326
327         /* Close any existing connections not at this level. */
328
329         for (tmp = cmd_list; tmp; tmp = tmp->next) {
330                 struct cmd_set *tmp_set;
331
332                 for (tmp_set = tmp->cmd_set; tmp_set->name; tmp_set++) {
333                         if (tmp_set->rpc_pipe == NULL) {
334                                 continue;
335                         }
336
337                         if (tmp_set->rpc_pipe->auth.auth_type != pipe_default_auth_type ||
338                                         tmp_set->rpc_pipe->auth.auth_level != pipe_default_auth_level) {
339                                 cli_rpc_pipe_close(tmp_set->rpc_pipe);
340                                 tmp_set->rpc_pipe = NULL;
341                         }
342                 }
343         }
344         return NT_STATUS_OK;
345 }
346
347 static NTSTATUS cmd_sign(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
348                          int argc, const char **argv)
349 {
350         pipe_default_auth_level = PIPE_AUTH_LEVEL_INTEGRITY;
351         pipe_default_auth_type = PIPE_AUTH_TYPE_NTLMSSP;
352
353         if (argc > 2) {
354                 printf("Usage: %s [NTLMSSP|NTLMSSP_SPNEGO|SCHANNEL]\n", argv[0]);
355                 return NT_STATUS_OK;
356         }
357
358         if (argc == 2) {
359                 if (strequal(argv[1], "NTLMSSP")) {
360                         pipe_default_auth_type = PIPE_AUTH_TYPE_NTLMSSP;
361                 } else if (strequal(argv[1], "NTLMSSP_SPNEGO")) {
362                         pipe_default_auth_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
363                 } else if (strequal(argv[1], "SCHANNEL")) {
364                         pipe_default_auth_type = PIPE_AUTH_TYPE_SCHANNEL;
365                 } else {
366                         printf("unknown type %s\n", argv[1]);
367                         return NT_STATUS_INVALID_LEVEL;
368                 }
369         }
370
371         printf("debuglevel is %d\n", DEBUGLEVEL);
372         return cmd_set_ss_level();
373 }
374
375 static NTSTATUS cmd_seal(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
376                          int argc, const char **argv)
377 {
378         pipe_default_auth_level = PIPE_AUTH_LEVEL_PRIVACY;
379         pipe_default_auth_type = PIPE_AUTH_TYPE_NTLMSSP;
380
381         if (argc > 2) {
382                 printf("Usage: %s [NTLMSSP|NTLMSSP_SPNEGO|SCHANNEL]\n", argv[0]);
383                 return NT_STATUS_OK;
384         }
385
386         if (argc == 2) {
387                 if (strequal(argv[1], "NTLMSSP")) {
388                         pipe_default_auth_type = PIPE_AUTH_TYPE_NTLMSSP;
389                 } else if (strequal(argv[1], "NTLMSSP_SPNEGO")) {
390                         pipe_default_auth_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
391                 } else if (strequal(argv[1], "SCHANNEL")) {
392                         pipe_default_auth_type = PIPE_AUTH_TYPE_SCHANNEL;
393                 } else {
394                         printf("unknown type %s\n", argv[1]);
395                         return NT_STATUS_INVALID_LEVEL;
396                 }
397         }
398         return cmd_set_ss_level();
399 }
400
401 static NTSTATUS cmd_timeout(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
402                             int argc, const char **argv)
403 {
404         struct cmd_list *tmp;
405
406         if (argc > 2) {
407                 printf("Usage: %s timeout\n", argv[0]);
408                 return NT_STATUS_OK;
409         }
410
411         if (argc == 2) {
412                 timeout = atoi(argv[1]);
413
414                 for (tmp = cmd_list; tmp; tmp = tmp->next) {
415                         
416                         struct cmd_set *tmp_set;
417
418                         for (tmp_set = tmp->cmd_set; tmp_set->name; tmp_set++) {
419                                 if (tmp_set->rpc_pipe == NULL) {
420                                         continue;
421                                 }
422
423                                 cli_set_timeout(tmp_set->rpc_pipe->cli, timeout);
424                         }
425                 }
426         }
427
428         printf("timeout is %d\n", timeout);
429
430         return NT_STATUS_OK;
431 }
432
433
434 static NTSTATUS cmd_none(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
435                          int argc, const char **argv)
436 {
437         pipe_default_auth_level = PIPE_AUTH_LEVEL_NONE;
438         pipe_default_auth_type = PIPE_AUTH_TYPE_NONE;
439
440         return cmd_set_ss_level();
441 }
442
443 static NTSTATUS cmd_schannel(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
444                              int argc, const char **argv)
445 {
446         d_printf("Setting schannel - sign and seal\n");
447         pipe_default_auth_level = PIPE_AUTH_LEVEL_PRIVACY;
448         pipe_default_auth_type = PIPE_AUTH_TYPE_SCHANNEL;
449
450         return cmd_set_ss_level();
451 }
452
453 static NTSTATUS cmd_schannel_sign(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
454                              int argc, const char **argv)
455 {
456         d_printf("Setting schannel - sign only\n");
457         pipe_default_auth_level = PIPE_AUTH_LEVEL_INTEGRITY;
458         pipe_default_auth_type = PIPE_AUTH_TYPE_SCHANNEL;
459
460         return cmd_set_ss_level();
461 }
462
463
464 /* Built in rpcclient commands */
465
466 static struct cmd_set rpcclient_commands[] = {
467
468         { "GENERAL OPTIONS" },
469
470         { "help", RPC_RTYPE_NTSTATUS, cmd_help, NULL,     -1, NULL,     "Get help on commands", "[command]" },
471         { "?",  RPC_RTYPE_NTSTATUS, cmd_help, NULL,       -1, NULL,     "Get help on commands", "[command]" },
472         { "debuglevel", RPC_RTYPE_NTSTATUS, cmd_debuglevel, NULL,   -1, NULL, "Set debug level", "level" },
473         { "debug", RPC_RTYPE_NTSTATUS, cmd_debuglevel, NULL,   -1,      NULL, "Set debug level", "level" },
474         { "list",       RPC_RTYPE_NTSTATUS, cmd_listcommands, NULL, -1, NULL, "List available commands on <pipe>", "pipe" },
475         { "exit", RPC_RTYPE_NTSTATUS, cmd_quit, NULL,   -1,     NULL,   "Exit program", "" },
476         { "quit", RPC_RTYPE_NTSTATUS, cmd_quit, NULL,     -1,   NULL, "Exit program", "" },
477         { "sign", RPC_RTYPE_NTSTATUS, cmd_sign, NULL,     -1,   NULL, "Force RPC pipe connections to be signed", "" },
478         { "seal", RPC_RTYPE_NTSTATUS, cmd_seal, NULL,     -1,   NULL, "Force RPC pipe connections to be sealed", "" },
479         { "schannel", RPC_RTYPE_NTSTATUS, cmd_schannel, NULL,     -1, NULL,     "Force RPC pipe connections to be sealed with 'schannel'.  Assumes valid machine account to this domain controller.", "" },
480         { "schannelsign", RPC_RTYPE_NTSTATUS, cmd_schannel_sign, NULL,    -1, NULL, "Force RPC pipe connections to be signed (not sealed) with 'schannel'.  Assumes valid machine account to this domain controller.", "" },
481         { "timeout", RPC_RTYPE_NTSTATUS, cmd_timeout, NULL,       -1, NULL, "Set timeout (in milliseonds) for RPC operations", "" },
482         { "none", RPC_RTYPE_NTSTATUS, cmd_none, NULL,     -1, NULL, "Force RPC pipe connections to have no special properties", "" },
483
484         { NULL }
485 };
486
487 static struct cmd_set separator_command[] = {
488         { "---------------", MAX_RPC_RETURN_TYPE, NULL, NULL,   -1, NULL, "----------------------" },
489         { NULL }
490 };
491
492
493 /* Various pipe commands */
494
495 extern struct cmd_set lsarpc_commands[];
496 extern struct cmd_set samr_commands[];
497 extern struct cmd_set spoolss_commands[];
498 extern struct cmd_set netlogon_commands[];
499 extern struct cmd_set srvsvc_commands[];
500 extern struct cmd_set dfs_commands[];
501 extern struct cmd_set ds_commands[];
502 extern struct cmd_set echo_commands[];
503 extern struct cmd_set shutdown_commands[];
504 extern struct cmd_set test_commands[];
505 extern struct cmd_set wkssvc_commands[];
506 extern struct cmd_set ntsvcs_commands[];
507
508 static struct cmd_set *rpcclient_command_list[] = {
509         rpcclient_commands,
510         lsarpc_commands,
511         ds_commands,
512         samr_commands,
513         spoolss_commands,
514         netlogon_commands,
515         srvsvc_commands,
516         dfs_commands,
517         echo_commands,
518         shutdown_commands,
519         test_commands,
520         wkssvc_commands,
521         ntsvcs_commands,
522         NULL
523 };
524
525 static void add_command_set(struct cmd_set *cmd_set)
526 {
527         struct cmd_list *entry;
528
529         if (!(entry = SMB_MALLOC_P(struct cmd_list))) {
530                 DEBUG(0, ("out of memory\n"));
531                 return;
532         }
533
534         ZERO_STRUCTP(entry);
535
536         entry->cmd_set = cmd_set;
537         DLIST_ADD(cmd_list, entry);
538 }
539
540
541 /**
542  * Call an rpcclient function, passing an argv array.
543  *
544  * @param cmd Command to run, as a single string.
545  **/
546 static NTSTATUS do_cmd(struct cli_state *cli,
547                        struct cmd_set *cmd_entry,
548                        int argc, char **argv)
549 {
550         NTSTATUS ntresult;
551         WERROR wresult;
552         
553         TALLOC_CTX *mem_ctx;
554
555         /* Create mem_ctx */
556
557         if (!(mem_ctx = talloc_init("do_cmd"))) {
558                 DEBUG(0, ("talloc_init() failed\n"));
559                 return NT_STATUS_NO_MEMORY;
560         }
561
562         /* Open pipe */
563
564         if (cmd_entry->pipe_idx != -1 && cmd_entry->rpc_pipe == NULL) {
565                 switch (pipe_default_auth_type) {
566                         case PIPE_AUTH_TYPE_NONE:
567                                 cmd_entry->rpc_pipe = cli_rpc_pipe_open_noauth(cli,
568                                                                 cmd_entry->pipe_idx,
569                                                                 &ntresult);
570                                 break;
571                         case PIPE_AUTH_TYPE_SPNEGO_NTLMSSP:
572                                 cmd_entry->rpc_pipe = cli_rpc_pipe_open_spnego_ntlmssp(cli,
573                                                                 cmd_entry->pipe_idx,
574                                                                 pipe_default_auth_level,
575                                                                 lp_workgroup(),
576                                                                 get_cmdline_auth_info_username(),
577                                                                 get_cmdline_auth_info_password(),
578                                                                 &ntresult);
579                                 break;
580                         case PIPE_AUTH_TYPE_NTLMSSP:
581                                 cmd_entry->rpc_pipe = cli_rpc_pipe_open_ntlmssp(cli,
582                                                                 cmd_entry->pipe_idx,
583                                                                 pipe_default_auth_level,
584                                                                 lp_workgroup(),
585                                                                 get_cmdline_auth_info_username(),
586                                                                 get_cmdline_auth_info_password(),
587                                                                 &ntresult);
588                                 break;
589                         case PIPE_AUTH_TYPE_SCHANNEL:
590                                 cmd_entry->rpc_pipe = cli_rpc_pipe_open_schannel(cli,
591                                                                 cmd_entry->pipe_idx,
592                                                                 pipe_default_auth_level,
593                                                                 lp_workgroup(),
594                                                                 &ntresult);
595                                 break;
596                         default:
597                                 DEBUG(0, ("Could not initialise %s. Invalid auth type %u\n",
598                                         cli_get_pipe_name(cmd_entry->pipe_idx),
599                                         pipe_default_auth_type ));
600                                 return NT_STATUS_UNSUCCESSFUL;
601                 }
602                 if (!cmd_entry->rpc_pipe) {
603                         DEBUG(0, ("Could not initialise %s. Error was %s\n",
604                                 cli_get_pipe_name(cmd_entry->pipe_idx),
605                                 nt_errstr(ntresult) ));
606                         return ntresult;
607                 }
608
609                 if (cmd_entry->pipe_idx == PI_NETLOGON) {
610                         uint32 neg_flags = NETLOGON_NEG_SELECT_AUTH2_FLAGS;
611                         uint32 sec_channel_type;
612                         uchar trust_password[16];
613         
614                         if (!secrets_fetch_trust_account_password(lp_workgroup(),
615                                                         trust_password,
616                                                         NULL, &sec_channel_type)) {
617                                 return NT_STATUS_UNSUCCESSFUL;
618                         }
619                 
620                         ntresult = rpccli_netlogon_setup_creds(cmd_entry->rpc_pipe,
621                                                 cli->desthost,   /* server name */
622                                                 lp_workgroup(),  /* domain */
623                                                 global_myname(), /* client name */
624                                                 global_myname(), /* machine account name */
625                                                 trust_password,
626                                                 sec_channel_type,
627                                                 &neg_flags);
628
629                         if (!NT_STATUS_IS_OK(ntresult)) {
630                                 DEBUG(0, ("Could not initialise credentials for %s.\n",
631                                         cli_get_pipe_name(cmd_entry->pipe_idx)));
632                                 return ntresult;
633                         }
634                 }
635         }
636
637         /* Run command */
638
639         if ( cmd_entry->returntype == RPC_RTYPE_NTSTATUS ) {
640                 ntresult = cmd_entry->ntfn(cmd_entry->rpc_pipe, mem_ctx, argc, (const char **) argv);
641                 if (!NT_STATUS_IS_OK(ntresult)) {
642                         printf("result was %s\n", nt_errstr(ntresult));
643                 }
644         } else {
645                 wresult = cmd_entry->wfn(cmd_entry->rpc_pipe, mem_ctx, argc, (const char **) argv);
646                 /* print out the DOS error */
647                 if (!W_ERROR_IS_OK(wresult)) {
648                         printf( "result was %s\n", dos_errstr(wresult));
649                 }
650                 ntresult = W_ERROR_IS_OK(wresult)?NT_STATUS_OK:NT_STATUS_UNSUCCESSFUL;
651         }
652
653         /* Cleanup */
654
655         talloc_destroy(mem_ctx);
656
657         return ntresult;
658 }
659
660
661 /**
662  * Process a command entered at the prompt or as part of -c
663  *
664  * @returns The NTSTATUS from running the command.
665  **/
666 static NTSTATUS process_cmd(struct cli_state *cli, char *cmd)
667 {
668         struct cmd_list *temp_list;
669         NTSTATUS result = NT_STATUS_OK;
670         int ret;
671         int argc;
672         char **argv = NULL;
673
674         if ((ret = poptParseArgvString(cmd, &argc, (const char ***) &argv)) != 0) {
675                 fprintf(stderr, "rpcclient: %s\n", poptStrerror(ret));
676                 return NT_STATUS_UNSUCCESSFUL;
677         }
678
679
680         /* Walk through a dlist of arrays of commands. */
681         for (temp_list = cmd_list; temp_list; temp_list = temp_list->next) {
682                 struct cmd_set *temp_set = temp_list->cmd_set;
683
684                 while (temp_set->name) {
685                         if (strequal(argv[0], temp_set->name)) {
686                                 if (!(temp_set->returntype == RPC_RTYPE_NTSTATUS && temp_set->ntfn ) &&
687                          !(temp_set->returntype == RPC_RTYPE_WERROR && temp_set->wfn )) {
688                                         fprintf (stderr, "Invalid command\n");
689                                         goto out_free;
690                                 }
691
692                                 result = do_cmd(cli, temp_set, argc, argv);
693
694                                 goto out_free;
695                         }
696                         temp_set++;
697                 }
698         }
699
700         if (argv[0]) {
701                 printf("command not found: %s\n", argv[0]);
702         }
703
704 out_free:
705 /* moved to do_cmd()
706         if (!NT_STATUS_IS_OK(result)) {
707                 printf("result was %s\n", nt_errstr(result));
708         }
709 */
710
711         /* NOTE: popt allocates the whole argv, including the
712          * strings, as a single block.  So a single free is
713          * enough to release it -- we don't free the
714          * individual strings.  rtfm. */
715         free(argv);
716
717         return result;
718 }
719
720
721 /* Main function */
722
723  int main(int argc, char *argv[])
724 {
725         int                     opt;
726         static char             *cmdstr = NULL;
727         const char *server;
728         struct cli_state        *cli = NULL;
729         static char             *opt_ipaddr=NULL;
730         struct cmd_set          **cmd_set;
731         struct sockaddr_storage server_ss;
732         NTSTATUS                nt_status;
733         static int              opt_port = 0;
734         fstring new_workgroup;
735         int result = 0;
736         TALLOC_CTX *frame = talloc_stackframe();
737
738         /* make sure the vars that get altered (4th field) are in
739            a fixed location or certain compilers complain */
740         poptContext pc;
741         struct poptOption long_options[] = {
742                 POPT_AUTOHELP
743                 {"command",     'c', POPT_ARG_STRING,   &cmdstr, 'c', "Execute semicolon separated cmds", "COMMANDS"},
744                 {"dest-ip", 'I', POPT_ARG_STRING,   &opt_ipaddr, 'I', "Specify destination IP address", "IP"},
745                 {"port", 'p', POPT_ARG_INT,   &opt_port, 'p', "Specify port number", "PORT"},
746                 POPT_COMMON_SAMBA
747                 POPT_COMMON_CONNECTION
748                 POPT_COMMON_CREDENTIALS
749                 POPT_TABLEEND
750         };
751
752         load_case_tables();
753
754         zero_addr(&server_ss);
755
756         setlinebuf(stdout);
757
758         /* the following functions are part of the Samba debugging
759            facilities.  See lib/debug.c */
760         setup_logging("rpcclient", True);
761
762         /* Parse options */
763
764         pc = poptGetContext("rpcclient", argc, (const char **) argv,
765                             long_options, 0);
766
767         if (argc == 1) {
768                 poptPrintHelp(pc, stderr, 0);
769                 goto done;
770         }
771
772         while((opt = poptGetNextOpt(pc)) != -1) {
773                 switch (opt) {
774
775                 case 'I':
776                         if (!interpret_string_addr(&server_ss,
777                                                 opt_ipaddr,
778                                                 AI_NUMERICHOST)) {
779                                 fprintf(stderr, "%s not a valid IP address\n",
780                                         opt_ipaddr);
781                                 result = 1;
782                                 goto done;
783                         }
784                 }
785         }
786
787         /* Get server as remaining unparsed argument.  Print usage if more
788            than one unparsed argument is present. */
789
790         server = poptGetArg(pc);
791
792         if (!server || poptGetArg(pc)) {
793                 poptPrintHelp(pc, stderr, 0);
794                 result = 1;
795                 goto done;
796         }
797
798         poptFreeContext(pc);
799
800         load_interfaces();
801
802         if (!init_names()) {
803                 result = 1;
804                 goto done;
805         }
806
807         /* save the workgroup...
808
809            FIXME!! do we need to do this for other options as well
810            (or maybe a generic way to keep lp_load() from overwriting
811            everything)?  */
812
813         fstrcpy( new_workgroup, lp_workgroup() );
814
815         /* Load smb.conf file */
816
817         if (!lp_load(get_dyn_CONFIGFILE(),True,False,False,True))
818                 fprintf(stderr, "Can't load %s\n", get_dyn_CONFIGFILE());
819
820         if ( strlen(new_workgroup) != 0 )
821                 set_global_myworkgroup( new_workgroup );
822
823         /*
824          * Get password
825          * from stdin if necessary
826          */
827
828         if (!get_cmdline_auth_info_got_pass()) {
829                 char *pass = getpass("Password:");
830                 if (pass) {
831                         set_cmdline_auth_info_password(pass);
832                 }
833         }
834
835         if ((server[0] == '/' && server[1] == '/') ||
836                         (server[0] == '\\' && server[1] ==  '\\')) {
837                 server += 2;
838         }
839
840         nt_status = cli_full_connection(&cli, global_myname(), server,
841                                         opt_ipaddr ? &server_ss : NULL, opt_port,
842                                         "IPC$", "IPC",
843                                         get_cmdline_auth_info_username(),
844                                         lp_workgroup(),
845                                         get_cmdline_auth_info_password(),
846                                         get_cmdline_auth_info_use_kerberos() ? CLI_FULL_CONNECTION_USE_KERBEROS : 0,
847                                         get_cmdline_auth_info_signing_state(),NULL);
848
849         if (!NT_STATUS_IS_OK(nt_status)) {
850                 DEBUG(0,("Cannot connect to server.  Error was %s\n", nt_errstr(nt_status)));
851                 result = 1;
852                 goto done;
853         }
854
855         if (get_cmdline_auth_info_smb_encrypt()) {
856                 nt_status = cli_cm_force_encryption(cli,
857                                         get_cmdline_auth_info_username(),
858                                         get_cmdline_auth_info_password(),
859                                         lp_workgroup(),
860                                         "IPC$");
861                 if (!NT_STATUS_IS_OK(nt_status)) {
862                         result = 1;
863                         goto done;
864                 }
865         }
866
867 #if 0   /* COMMENT OUT FOR TESTING */
868         memset(cmdline_auth_info.password,'X',sizeof(cmdline_auth_info.password));
869 #endif
870
871         /* Load command lists */
872
873         timeout = cli_set_timeout(cli, 10000);
874
875         cmd_set = rpcclient_command_list;
876
877         while(*cmd_set) {
878                 add_command_set(*cmd_set);
879                 add_command_set(separator_command);
880                 cmd_set++;
881         }
882
883         fetch_machine_sid(cli);
884
885        /* Do anything specified with -c */
886         if (cmdstr && cmdstr[0]) {
887                 char    *cmd;
888                 char    *p = cmdstr;
889
890                 result = 0;
891
892                 while((cmd=next_command(&p)) != NULL) {
893                         NTSTATUS cmd_result = process_cmd(cli, cmd);
894                         SAFE_FREE(cmd);
895                         result = NT_STATUS_IS_ERR(cmd_result);
896                 }
897
898                 goto done;
899         }
900
901         /* Loop around accepting commands */
902
903         while(1) {
904                 char *line = NULL;
905
906                 line = smb_readline("rpcclient $> ", NULL, completion_fn);
907
908                 if (line == NULL)
909                         break;
910
911                 if (line[0] != '\n')
912                         process_cmd(cli, line);
913                 SAFE_FREE(line);
914         }
915
916 done:
917         if (cli != NULL) {
918                 cli_shutdown(cli);
919         }
920         TALLOC_FREE(frame);
921         return result;
922 }