Fix client authentication with -P switch in client tools (Bug 5435).
[amitay/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         TALLOC_FREE(lsapipe);
173         talloc_destroy(mem_ctx);
174
175         return;
176
177  error:
178
179         if (lsapipe) {
180                 TALLOC_FREE(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
338                              != pipe_default_auth_type)
339                             || (tmp_set->rpc_pipe->auth->auth_level
340                                 != pipe_default_auth_level)) {
341                                 TALLOC_FREE(tmp_set->rpc_pipe);
342                                 tmp_set->rpc_pipe = NULL;
343                         }
344                 }
345         }
346         return NT_STATUS_OK;
347 }
348
349 static NTSTATUS cmd_sign(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
350                          int argc, const char **argv)
351 {
352         pipe_default_auth_level = PIPE_AUTH_LEVEL_INTEGRITY;
353         pipe_default_auth_type = PIPE_AUTH_TYPE_NTLMSSP;
354
355         if (argc > 2) {
356                 printf("Usage: %s [NTLMSSP|NTLMSSP_SPNEGO|SCHANNEL]\n", argv[0]);
357                 return NT_STATUS_OK;
358         }
359
360         if (argc == 2) {
361                 if (strequal(argv[1], "NTLMSSP")) {
362                         pipe_default_auth_type = PIPE_AUTH_TYPE_NTLMSSP;
363                 } else if (strequal(argv[1], "NTLMSSP_SPNEGO")) {
364                         pipe_default_auth_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
365                 } else if (strequal(argv[1], "SCHANNEL")) {
366                         pipe_default_auth_type = PIPE_AUTH_TYPE_SCHANNEL;
367                 } else {
368                         printf("unknown type %s\n", argv[1]);
369                         return NT_STATUS_INVALID_LEVEL;
370                 }
371         }
372
373         printf("debuglevel is %d\n", DEBUGLEVEL);
374         return cmd_set_ss_level();
375 }
376
377 static NTSTATUS cmd_seal(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
378                          int argc, const char **argv)
379 {
380         pipe_default_auth_level = PIPE_AUTH_LEVEL_PRIVACY;
381         pipe_default_auth_type = PIPE_AUTH_TYPE_NTLMSSP;
382
383         if (argc > 2) {
384                 printf("Usage: %s [NTLMSSP|NTLMSSP_SPNEGO|SCHANNEL]\n", argv[0]);
385                 return NT_STATUS_OK;
386         }
387
388         if (argc == 2) {
389                 if (strequal(argv[1], "NTLMSSP")) {
390                         pipe_default_auth_type = PIPE_AUTH_TYPE_NTLMSSP;
391                 } else if (strequal(argv[1], "NTLMSSP_SPNEGO")) {
392                         pipe_default_auth_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
393                 } else if (strequal(argv[1], "SCHANNEL")) {
394                         pipe_default_auth_type = PIPE_AUTH_TYPE_SCHANNEL;
395                 } else {
396                         printf("unknown type %s\n", argv[1]);
397                         return NT_STATUS_INVALID_LEVEL;
398                 }
399         }
400         return cmd_set_ss_level();
401 }
402
403 static NTSTATUS cmd_timeout(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
404                             int argc, const char **argv)
405 {
406         struct cmd_list *tmp;
407
408         if (argc > 2) {
409                 printf("Usage: %s timeout\n", argv[0]);
410                 return NT_STATUS_OK;
411         }
412
413         if (argc == 2) {
414                 timeout = atoi(argv[1]);
415
416                 for (tmp = cmd_list; tmp; tmp = tmp->next) {
417                         
418                         struct cmd_set *tmp_set;
419
420                         for (tmp_set = tmp->cmd_set; tmp_set->name; tmp_set++) {
421                                 if (tmp_set->rpc_pipe == NULL) {
422                                         continue;
423                                 }
424
425                                 rpccli_set_timeout(tmp_set->rpc_pipe, timeout);
426                         }
427                 }
428         }
429
430         printf("timeout is %d\n", timeout);
431
432         return NT_STATUS_OK;
433 }
434
435
436 static NTSTATUS cmd_none(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
437                          int argc, const char **argv)
438 {
439         pipe_default_auth_level = PIPE_AUTH_LEVEL_NONE;
440         pipe_default_auth_type = PIPE_AUTH_TYPE_NONE;
441
442         return cmd_set_ss_level();
443 }
444
445 static NTSTATUS cmd_schannel(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
446                              int argc, const char **argv)
447 {
448         d_printf("Setting schannel - sign and seal\n");
449         pipe_default_auth_level = PIPE_AUTH_LEVEL_PRIVACY;
450         pipe_default_auth_type = PIPE_AUTH_TYPE_SCHANNEL;
451
452         return cmd_set_ss_level();
453 }
454
455 static NTSTATUS cmd_schannel_sign(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
456                              int argc, const char **argv)
457 {
458         d_printf("Setting schannel - sign only\n");
459         pipe_default_auth_level = PIPE_AUTH_LEVEL_INTEGRITY;
460         pipe_default_auth_type = PIPE_AUTH_TYPE_SCHANNEL;
461
462         return cmd_set_ss_level();
463 }
464
465
466 /* Built in rpcclient commands */
467
468 static struct cmd_set rpcclient_commands[] = {
469
470         { "GENERAL OPTIONS" },
471
472         { "help", RPC_RTYPE_NTSTATUS, cmd_help, NULL,     -1, NULL,     "Get help on commands", "[command]" },
473         { "?",  RPC_RTYPE_NTSTATUS, cmd_help, NULL,       -1, NULL,     "Get help on commands", "[command]" },
474         { "debuglevel", RPC_RTYPE_NTSTATUS, cmd_debuglevel, NULL,   -1, NULL, "Set debug level", "level" },
475         { "debug", RPC_RTYPE_NTSTATUS, cmd_debuglevel, NULL,   -1,      NULL, "Set debug level", "level" },
476         { "list",       RPC_RTYPE_NTSTATUS, cmd_listcommands, NULL, -1, NULL, "List available commands on <pipe>", "pipe" },
477         { "exit", RPC_RTYPE_NTSTATUS, cmd_quit, NULL,   -1,     NULL,   "Exit program", "" },
478         { "quit", RPC_RTYPE_NTSTATUS, cmd_quit, NULL,     -1,   NULL, "Exit program", "" },
479         { "sign", RPC_RTYPE_NTSTATUS, cmd_sign, NULL,     -1,   NULL, "Force RPC pipe connections to be signed", "" },
480         { "seal", RPC_RTYPE_NTSTATUS, cmd_seal, NULL,     -1,   NULL, "Force RPC pipe connections to be sealed", "" },
481         { "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.", "" },
482         { "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.", "" },
483         { "timeout", RPC_RTYPE_NTSTATUS, cmd_timeout, NULL,       -1, NULL, "Set timeout (in milliseonds) for RPC operations", "" },
484         { "none", RPC_RTYPE_NTSTATUS, cmd_none, NULL,     -1, NULL, "Force RPC pipe connections to have no special properties", "" },
485
486         { NULL }
487 };
488
489 static struct cmd_set separator_command[] = {
490         { "---------------", MAX_RPC_RETURN_TYPE, NULL, NULL,   -1, NULL, "----------------------" },
491         { NULL }
492 };
493
494
495 /* Various pipe commands */
496
497 extern struct cmd_set lsarpc_commands[];
498 extern struct cmd_set samr_commands[];
499 extern struct cmd_set spoolss_commands[];
500 extern struct cmd_set netlogon_commands[];
501 extern struct cmd_set srvsvc_commands[];
502 extern struct cmd_set dfs_commands[];
503 extern struct cmd_set ds_commands[];
504 extern struct cmd_set echo_commands[];
505 extern struct cmd_set shutdown_commands[];
506 extern struct cmd_set test_commands[];
507 extern struct cmd_set wkssvc_commands[];
508 extern struct cmd_set ntsvcs_commands[];
509
510 static struct cmd_set *rpcclient_command_list[] = {
511         rpcclient_commands,
512         lsarpc_commands,
513         ds_commands,
514         samr_commands,
515         spoolss_commands,
516         netlogon_commands,
517         srvsvc_commands,
518         dfs_commands,
519         echo_commands,
520         shutdown_commands,
521         test_commands,
522         wkssvc_commands,
523         ntsvcs_commands,
524         NULL
525 };
526
527 static void add_command_set(struct cmd_set *cmd_set)
528 {
529         struct cmd_list *entry;
530
531         if (!(entry = SMB_MALLOC_P(struct cmd_list))) {
532                 DEBUG(0, ("out of memory\n"));
533                 return;
534         }
535
536         ZERO_STRUCTP(entry);
537
538         entry->cmd_set = cmd_set;
539         DLIST_ADD(cmd_list, entry);
540 }
541
542
543 /**
544  * Call an rpcclient function, passing an argv array.
545  *
546  * @param cmd Command to run, as a single string.
547  **/
548 static NTSTATUS do_cmd(struct cli_state *cli,
549                        struct cmd_set *cmd_entry,
550                        int argc, char **argv)
551 {
552         NTSTATUS ntresult;
553         WERROR wresult;
554         
555         TALLOC_CTX *mem_ctx;
556
557         /* Create mem_ctx */
558
559         if (!(mem_ctx = talloc_init("do_cmd"))) {
560                 DEBUG(0, ("talloc_init() failed\n"));
561                 return NT_STATUS_NO_MEMORY;
562         }
563
564         /* Open pipe */
565
566         if (cmd_entry->pipe_idx != -1 && cmd_entry->rpc_pipe == NULL) {
567                 switch (pipe_default_auth_type) {
568                         case PIPE_AUTH_TYPE_NONE:
569                                 cmd_entry->rpc_pipe = cli_rpc_pipe_open_noauth(cli,
570                                                                 cmd_entry->pipe_idx,
571                                                                 &ntresult);
572                                 break;
573                         case PIPE_AUTH_TYPE_SPNEGO_NTLMSSP:
574                                 cmd_entry->rpc_pipe = cli_rpc_pipe_open_spnego_ntlmssp(cli,
575                                                                 cmd_entry->pipe_idx,
576                                                                 pipe_default_auth_level,
577                                                                 lp_workgroup(),
578                                                                 get_cmdline_auth_info_username(),
579                                                                 get_cmdline_auth_info_password(),
580                                                                 &ntresult);
581                                 break;
582                         case PIPE_AUTH_TYPE_NTLMSSP:
583                                 cmd_entry->rpc_pipe = cli_rpc_pipe_open_ntlmssp(cli,
584                                                                 cmd_entry->pipe_idx,
585                                                                 pipe_default_auth_level,
586                                                                 lp_workgroup(),
587                                                                 get_cmdline_auth_info_username(),
588                                                                 get_cmdline_auth_info_password(),
589                                                                 &ntresult);
590                                 break;
591                         case PIPE_AUTH_TYPE_SCHANNEL:
592                                 cmd_entry->rpc_pipe = cli_rpc_pipe_open_schannel(cli,
593                                                                 cmd_entry->pipe_idx,
594                                                                 pipe_default_auth_level,
595                                                                 lp_workgroup(),
596                                                                 &ntresult);
597                                 break;
598                         default:
599                                 DEBUG(0, ("Could not initialise %s. Invalid auth type %u\n",
600                                         cli_get_pipe_name(cmd_entry->pipe_idx),
601                                         pipe_default_auth_type ));
602                                 return NT_STATUS_UNSUCCESSFUL;
603                 }
604                 if (!cmd_entry->rpc_pipe) {
605                         DEBUG(0, ("Could not initialise %s. Error was %s\n",
606                                 cli_get_pipe_name(cmd_entry->pipe_idx),
607                                 nt_errstr(ntresult) ));
608                         return ntresult;
609                 }
610
611                 if (cmd_entry->pipe_idx == PI_NETLOGON) {
612                         uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
613                         uint32 sec_channel_type;
614                         uchar trust_password[16];
615         
616                         if (!secrets_fetch_trust_account_password(lp_workgroup(),
617                                                         trust_password,
618                                                         NULL, &sec_channel_type)) {
619                                 return NT_STATUS_UNSUCCESSFUL;
620                         }
621                 
622                         ntresult = rpccli_netlogon_setup_creds(cmd_entry->rpc_pipe,
623                                                 cli->desthost,   /* server name */
624                                                 lp_workgroup(),  /* domain */
625                                                 global_myname(), /* client name */
626                                                 global_myname(), /* machine account name */
627                                                 trust_password,
628                                                 sec_channel_type,
629                                                 &neg_flags);
630
631                         if (!NT_STATUS_IS_OK(ntresult)) {
632                                 DEBUG(0, ("Could not initialise credentials for %s.\n",
633                                         cli_get_pipe_name(cmd_entry->pipe_idx)));
634                                 return ntresult;
635                         }
636                 }
637         }
638
639         /* Run command */
640
641         if ( cmd_entry->returntype == RPC_RTYPE_NTSTATUS ) {
642                 ntresult = cmd_entry->ntfn(cmd_entry->rpc_pipe, mem_ctx, argc, (const char **) argv);
643                 if (!NT_STATUS_IS_OK(ntresult)) {
644                         printf("result was %s\n", nt_errstr(ntresult));
645                 }
646         } else {
647                 wresult = cmd_entry->wfn(cmd_entry->rpc_pipe, mem_ctx, argc, (const char **) argv);
648                 /* print out the DOS error */
649                 if (!W_ERROR_IS_OK(wresult)) {
650                         printf( "result was %s\n", dos_errstr(wresult));
651                 }
652                 ntresult = W_ERROR_IS_OK(wresult)?NT_STATUS_OK:NT_STATUS_UNSUCCESSFUL;
653         }
654
655         /* Cleanup */
656
657         talloc_destroy(mem_ctx);
658
659         return ntresult;
660 }
661
662
663 /**
664  * Process a command entered at the prompt or as part of -c
665  *
666  * @returns The NTSTATUS from running the command.
667  **/
668 static NTSTATUS process_cmd(struct cli_state *cli, char *cmd)
669 {
670         struct cmd_list *temp_list;
671         NTSTATUS result = NT_STATUS_OK;
672         int ret;
673         int argc;
674         char **argv = NULL;
675
676         if ((ret = poptParseArgvString(cmd, &argc, (const char ***) &argv)) != 0) {
677                 fprintf(stderr, "rpcclient: %s\n", poptStrerror(ret));
678                 return NT_STATUS_UNSUCCESSFUL;
679         }
680
681
682         /* Walk through a dlist of arrays of commands. */
683         for (temp_list = cmd_list; temp_list; temp_list = temp_list->next) {
684                 struct cmd_set *temp_set = temp_list->cmd_set;
685
686                 while (temp_set->name) {
687                         if (strequal(argv[0], temp_set->name)) {
688                                 if (!(temp_set->returntype == RPC_RTYPE_NTSTATUS && temp_set->ntfn ) &&
689                          !(temp_set->returntype == RPC_RTYPE_WERROR && temp_set->wfn )) {
690                                         fprintf (stderr, "Invalid command\n");
691                                         goto out_free;
692                                 }
693
694                                 result = do_cmd(cli, temp_set, argc, argv);
695
696                                 goto out_free;
697                         }
698                         temp_set++;
699                 }
700         }
701
702         if (argv[0]) {
703                 printf("command not found: %s\n", argv[0]);
704         }
705
706 out_free:
707 /* moved to do_cmd()
708         if (!NT_STATUS_IS_OK(result)) {
709                 printf("result was %s\n", nt_errstr(result));
710         }
711 */
712
713         /* NOTE: popt allocates the whole argv, including the
714          * strings, as a single block.  So a single free is
715          * enough to release it -- we don't free the
716          * individual strings.  rtfm. */
717         free(argv);
718
719         return result;
720 }
721
722
723 /* Main function */
724
725  int main(int argc, char *argv[])
726 {
727         int                     opt;
728         static char             *cmdstr = NULL;
729         const char *server;
730         struct cli_state        *cli = NULL;
731         static char             *opt_ipaddr=NULL;
732         struct cmd_set          **cmd_set;
733         struct sockaddr_storage server_ss;
734         NTSTATUS                nt_status;
735         static int              opt_port = 0;
736         fstring new_workgroup;
737         int result = 0;
738         TALLOC_CTX *frame = talloc_stackframe();
739         uint32_t flags = 0;
740
741         /* make sure the vars that get altered (4th field) are in
742            a fixed location or certain compilers complain */
743         poptContext pc;
744         struct poptOption long_options[] = {
745                 POPT_AUTOHELP
746                 {"command",     'c', POPT_ARG_STRING,   &cmdstr, 'c', "Execute semicolon separated cmds", "COMMANDS"},
747                 {"dest-ip", 'I', POPT_ARG_STRING,   &opt_ipaddr, 'I', "Specify destination IP address", "IP"},
748                 {"port", 'p', POPT_ARG_INT,   &opt_port, 'p', "Specify port number", "PORT"},
749                 POPT_COMMON_SAMBA
750                 POPT_COMMON_CONNECTION
751                 POPT_COMMON_CREDENTIALS
752                 POPT_TABLEEND
753         };
754
755         load_case_tables();
756
757         zero_addr(&server_ss);
758
759         setlinebuf(stdout);
760
761         /* the following functions are part of the Samba debugging
762            facilities.  See lib/debug.c */
763         setup_logging("rpcclient", True);
764
765         /* Parse options */
766
767         pc = poptGetContext("rpcclient", argc, (const char **) argv,
768                             long_options, 0);
769
770         if (argc == 1) {
771                 poptPrintHelp(pc, stderr, 0);
772                 goto done;
773         }
774
775         while((opt = poptGetNextOpt(pc)) != -1) {
776                 switch (opt) {
777
778                 case 'I':
779                         if (!interpret_string_addr(&server_ss,
780                                                 opt_ipaddr,
781                                                 AI_NUMERICHOST)) {
782                                 fprintf(stderr, "%s not a valid IP address\n",
783                                         opt_ipaddr);
784                                 result = 1;
785                                 goto done;
786                         }
787                 }
788         }
789
790         /* Get server as remaining unparsed argument.  Print usage if more
791            than one unparsed argument is present. */
792
793         server = poptGetArg(pc);
794
795         if (!server || poptGetArg(pc)) {
796                 poptPrintHelp(pc, stderr, 0);
797                 result = 1;
798                 goto done;
799         }
800
801         poptFreeContext(pc);
802
803         load_interfaces();
804
805         if (!init_names()) {
806                 result = 1;
807                 goto done;
808         }
809
810         /* save the workgroup...
811
812            FIXME!! do we need to do this for other options as well
813            (or maybe a generic way to keep lp_load() from overwriting
814            everything)?  */
815
816         fstrcpy( new_workgroup, lp_workgroup() );
817
818         /* Load smb.conf file */
819
820         if (!lp_load(get_dyn_CONFIGFILE(),True,False,False,True))
821                 fprintf(stderr, "Can't load %s\n", get_dyn_CONFIGFILE());
822
823         if ( strlen(new_workgroup) != 0 )
824                 set_global_myworkgroup( new_workgroup );
825
826         /*
827          * Get password
828          * from stdin if necessary
829          */
830
831         if (get_cmdline_auth_info_use_machine_account() &&
832             !set_cmdline_auth_info_machine_account_creds()) {
833                 result = 1;
834                 goto done;
835         }
836
837         if (!get_cmdline_auth_info_got_pass()) {
838                 char *pass = getpass("Password:");
839                 if (pass) {
840                         set_cmdline_auth_info_password(pass);
841                 }
842         }
843
844         if ((server[0] == '/' && server[1] == '/') ||
845                         (server[0] == '\\' && server[1] ==  '\\')) {
846                 server += 2;
847         }
848
849         if (get_cmdline_auth_info_use_kerberos()) {
850                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS |
851                          CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
852         }
853
854
855         nt_status = cli_full_connection(&cli, global_myname(), server,
856                                         opt_ipaddr ? &server_ss : NULL, opt_port,
857                                         "IPC$", "IPC",
858                                         get_cmdline_auth_info_username(),
859                                         lp_workgroup(),
860                                         get_cmdline_auth_info_password(),
861                                         flags,
862                                         get_cmdline_auth_info_signing_state(),NULL);
863
864         if (!NT_STATUS_IS_OK(nt_status)) {
865                 DEBUG(0,("Cannot connect to server.  Error was %s\n", nt_errstr(nt_status)));
866                 result = 1;
867                 goto done;
868         }
869
870         if (get_cmdline_auth_info_smb_encrypt()) {
871                 nt_status = cli_cm_force_encryption(cli,
872                                         get_cmdline_auth_info_username(),
873                                         get_cmdline_auth_info_password(),
874                                         lp_workgroup(),
875                                         "IPC$");
876                 if (!NT_STATUS_IS_OK(nt_status)) {
877                         result = 1;
878                         goto done;
879                 }
880         }
881
882 #if 0   /* COMMENT OUT FOR TESTING */
883         memset(cmdline_auth_info.password,'X',sizeof(cmdline_auth_info.password));
884 #endif
885
886         /* Load command lists */
887
888         timeout = cli_set_timeout(cli, 10000);
889
890         cmd_set = rpcclient_command_list;
891
892         while(*cmd_set) {
893                 add_command_set(*cmd_set);
894                 add_command_set(separator_command);
895                 cmd_set++;
896         }
897
898         fetch_machine_sid(cli);
899
900        /* Do anything specified with -c */
901         if (cmdstr && cmdstr[0]) {
902                 char    *cmd;
903                 char    *p = cmdstr;
904
905                 result = 0;
906
907                 while((cmd=next_command(&p)) != NULL) {
908                         NTSTATUS cmd_result = process_cmd(cli, cmd);
909                         SAFE_FREE(cmd);
910                         result = NT_STATUS_IS_ERR(cmd_result);
911                 }
912
913                 goto done;
914         }
915
916         /* Loop around accepting commands */
917
918         while(1) {
919                 char *line = NULL;
920
921                 line = smb_readline("rpcclient $> ", NULL, completion_fn);
922
923                 if (line == NULL)
924                         break;
925
926                 if (line[0] != '\n')
927                         process_cmd(cli, line);
928                 SAFE_FREE(line);
929         }
930
931 done:
932         if (cli != NULL) {
933                 cli_shutdown(cli);
934         }
935         TALLOC_FREE(frame);
936         return result;
937 }