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