s3 net: Fix compile warnings
[samba.git] / source3 / utils / net_rpc.c
1 /*
2    Samba Unix/Linux SMB client library
3    Distributed SMB/CIFS Server Management Utility
4    Copyright (C) 2001 Andrew Bartlett (abartlet@samba.org)
5    Copyright (C) 2002 Jim McDonough (jmcd@us.ibm.com)
6    Copyright (C) 2004,2008 Guenther Deschner (gd@samba.org)
7    Copyright (C) 2005 Jeremy Allison (jra@samba.org)
8    Copyright (C) 2006 Jelmer Vernooij (jelmer@samba.org)
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 #include "includes.h"
24 #include "utils/net.h"
25 #include "../libcli/auth/libcli_auth.h"
26 #include "../librpc/gen_ndr/cli_samr.h"
27 #include "../librpc/gen_ndr/cli_lsa.h"
28 #include "../librpc/gen_ndr/cli_netlogon.h"
29 #include "../librpc/gen_ndr/cli_srvsvc.h"
30 #include "../librpc/gen_ndr/cli_spoolss.h"
31 #include "../librpc/gen_ndr/cli_initshutdown.h"
32 #include "../librpc/gen_ndr/cli_winreg.h"
33
34 static int net_mode_share;
35 static bool sync_files(struct copy_clistate *cp_clistate, const char *mask);
36
37 /**
38  * @file net_rpc.c
39  *
40  * @brief RPC based subcommands for the 'net' utility.
41  *
42  * This file should contain much of the functionality that used to
43  * be found in rpcclient, execpt that the commands should change
44  * less often, and the fucntionality should be sane (the user is not
45  * expected to know a rid/sid before they conduct an operation etc.)
46  *
47  * @todo Perhaps eventually these should be split out into a number
48  * of files, as this could get quite big.
49  **/
50
51
52 /**
53  * Many of the RPC functions need the domain sid.  This function gets
54  *  it at the start of every run
55  *
56  * @param cli A cli_state already connected to the remote machine
57  *
58  * @return The Domain SID of the remote machine.
59  **/
60
61 NTSTATUS net_get_remote_domain_sid(struct cli_state *cli, TALLOC_CTX *mem_ctx,
62                                    DOM_SID **domain_sid,
63                                    const char **domain_name)
64 {
65         struct rpc_pipe_client *lsa_pipe = NULL;
66         struct policy_handle pol;
67         NTSTATUS result = NT_STATUS_OK;
68         union lsa_PolicyInformation *info = NULL;
69
70         result = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
71                                           &lsa_pipe);
72         if (!NT_STATUS_IS_OK(result)) {
73                 d_fprintf(stderr, _("Could not initialise lsa pipe\n"));
74                 return result;
75         }
76
77         result = rpccli_lsa_open_policy(lsa_pipe, mem_ctx, false,
78                                      SEC_FLAG_MAXIMUM_ALLOWED,
79                                      &pol);
80         if (!NT_STATUS_IS_OK(result)) {
81                 d_fprintf(stderr, "open_policy %s: %s\n",
82                           _("failed"),
83                           nt_errstr(result));
84                 return result;
85         }
86
87         result = rpccli_lsa_QueryInfoPolicy(lsa_pipe, mem_ctx,
88                                             &pol,
89                                             LSA_POLICY_INFO_ACCOUNT_DOMAIN,
90                                             &info);
91         if (!NT_STATUS_IS_OK(result)) {
92                 d_fprintf(stderr, "lsaquery %s: %s\n",
93                           _("failed"),
94                           nt_errstr(result));
95                 return result;
96         }
97
98         *domain_name = info->account_domain.name.string;
99         *domain_sid = info->account_domain.sid;
100
101         rpccli_lsa_Close(lsa_pipe, mem_ctx, &pol);
102         TALLOC_FREE(lsa_pipe);
103
104         return NT_STATUS_OK;
105 }
106
107 /**
108  * Run a single RPC command, from start to finish.
109  *
110  * @param pipe_name the pipe to connect to (usually a PIPE_ constant)
111  * @param conn_flag a NET_FLAG_ combination.  Passed to
112  *                   net_make_ipc_connection.
113  * @param argc  Standard main() style argc.
114  * @param argv  Standard main() style argv. Initial components are already
115  *              stripped.
116  * @return A shell status integer (0 for success).
117  */
118
119 int run_rpc_command(struct net_context *c,
120                         struct cli_state *cli_arg,
121                         const struct ndr_syntax_id *interface,
122                         int conn_flags,
123                         rpc_command_fn fn,
124                         int argc,
125                         const char **argv)
126 {
127         struct cli_state *cli = NULL;
128         struct rpc_pipe_client *pipe_hnd = NULL;
129         TALLOC_CTX *mem_ctx;
130         NTSTATUS nt_status;
131         DOM_SID *domain_sid;
132         const char *domain_name;
133         int ret = -1;
134
135         /* make use of cli_state handed over as an argument, if possible */
136         if (!cli_arg) {
137                 nt_status = net_make_ipc_connection(c, conn_flags, &cli);
138                 if (!NT_STATUS_IS_OK(nt_status)) {
139                         DEBUG(1, ("failed to make ipc connection: %s\n",
140                                   nt_errstr(nt_status)));
141                         return -1;
142                 }
143         } else {
144                 cli = cli_arg;
145         }
146
147         if (!cli) {
148                 return -1;
149         }
150
151         /* Create mem_ctx */
152
153         if (!(mem_ctx = talloc_init("run_rpc_command"))) {
154                 DEBUG(0, ("talloc_init() failed\n"));
155                 goto fail;
156         }
157
158         nt_status = net_get_remote_domain_sid(cli, mem_ctx, &domain_sid,
159                                               &domain_name);
160         if (!NT_STATUS_IS_OK(nt_status)) {
161                 goto fail;
162         }
163
164         if (!(conn_flags & NET_FLAGS_NO_PIPE)) {
165                 if (lp_client_schannel()
166                     && (ndr_syntax_id_equal(interface,
167                                             &ndr_table_netlogon.syntax_id))) {
168                         /* Always try and create an schannel netlogon pipe. */
169                         nt_status = cli_rpc_pipe_open_schannel(
170                                 cli, interface, NCACN_NP,
171                                 DCERPC_AUTH_LEVEL_PRIVACY, domain_name,
172                                 &pipe_hnd);
173                         if (!NT_STATUS_IS_OK(nt_status)) {
174                                 DEBUG(0, ("Could not initialise schannel netlogon pipe. Error was %s\n",
175                                         nt_errstr(nt_status) ));
176                                 goto fail;
177                         }
178                 } else {
179                         if (conn_flags & NET_FLAGS_SEAL) {
180                                 nt_status = cli_rpc_pipe_open_ntlmssp(
181                                         cli, interface,
182                                         (conn_flags & NET_FLAGS_TCP) ?
183                                         NCACN_IP_TCP : NCACN_NP,
184                                         DCERPC_AUTH_LEVEL_PRIVACY,
185                                         lp_workgroup(), c->opt_user_name,
186                                         c->opt_password, &pipe_hnd);
187                         } else {
188                                 nt_status = cli_rpc_pipe_open_noauth(
189                                         cli, interface,
190                                         &pipe_hnd);
191                         }
192                         if (!NT_STATUS_IS_OK(nt_status)) {
193                                 DEBUG(0, ("Could not initialise pipe %s. Error was %s\n",
194                                           get_pipe_name_from_syntax(
195                                                   talloc_tos(), interface),
196                                         nt_errstr(nt_status) ));
197                                 goto fail;
198                         }
199                 }
200         }
201
202         nt_status = fn(c, domain_sid, domain_name, cli, pipe_hnd, mem_ctx, argc, argv);
203
204         if (!NT_STATUS_IS_OK(nt_status)) {
205                 DEBUG(1, ("rpc command function failed! (%s)\n", nt_errstr(nt_status)));
206         } else {
207                 ret = 0;
208                 DEBUG(5, ("rpc command function succedded\n"));
209         }
210
211         if (!(conn_flags & NET_FLAGS_NO_PIPE)) {
212                 if (pipe_hnd) {
213                         TALLOC_FREE(pipe_hnd);
214                 }
215         }
216
217 fail:
218         /* close the connection only if it was opened here */
219         if (!cli_arg) {
220                 cli_shutdown(cli);
221         }
222
223         talloc_destroy(mem_ctx);
224         return ret;
225 }
226
227 /**
228  * Force a change of the trust acccount password.
229  *
230  * All parameters are provided by the run_rpc_command function, except for
231  * argc, argv which are passed through.
232  *
233  * @param domain_sid The domain sid acquired from the remote server.
234  * @param cli A cli_state connected to the server.
235  * @param mem_ctx Talloc context, destroyed on completion of the function.
236  * @param argc  Standard main() style argc.
237  * @param argv  Standard main() style argv. Initial components are already
238  *              stripped.
239  *
240  * @return Normal NTSTATUS return.
241  **/
242
243 static NTSTATUS rpc_changetrustpw_internals(struct net_context *c,
244                                         const DOM_SID *domain_sid,
245                                         const char *domain_name,
246                                         struct cli_state *cli,
247                                         struct rpc_pipe_client *pipe_hnd,
248                                         TALLOC_CTX *mem_ctx,
249                                         int argc,
250                                         const char **argv)
251 {
252         NTSTATUS status;
253
254         status = trust_pw_find_change_and_store_it(pipe_hnd, mem_ctx, c->opt_target_workgroup);
255         if (!NT_STATUS_IS_OK(status)) {
256                 d_fprintf(stderr, _("Failed to change machine account password: %s\n"),
257                         nt_errstr(status));
258                 return status;
259         }
260
261         return NT_STATUS_OK;
262 }
263
264 /**
265  * Force a change of the trust acccount password.
266  *
267  * @param argc  Standard main() style argc.
268  * @param argv  Standard main() style argv. Initial components are already
269  *              stripped.
270  *
271  * @return A shell status integer (0 for success).
272  **/
273
274 int net_rpc_changetrustpw(struct net_context *c, int argc, const char **argv)
275 {
276         if (c->display_usage) {
277                 d_printf(  "%s\n"
278                            "net rpc changetrustpw\n"
279                            "    %s\n",
280                          _("Usage:"),
281                          _("Change the machine trust password"));
282                 return 0;
283         }
284
285         return run_rpc_command(c, NULL, &ndr_table_netlogon.syntax_id,
286                                NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC,
287                                rpc_changetrustpw_internals,
288                                argc, argv);
289 }
290
291 /**
292  * Join a domain, the old way.
293  *
294  * This uses 'machinename' as the inital password, and changes it.
295  *
296  * The password should be created with 'server manager' or equiv first.
297  *
298  * All parameters are provided by the run_rpc_command function, except for
299  * argc, argv which are passed through.
300  *
301  * @param domain_sid The domain sid acquired from the remote server.
302  * @param cli A cli_state connected to the server.
303  * @param mem_ctx Talloc context, destroyed on completion of the function.
304  * @param argc  Standard main() style argc.
305  * @param argv  Standard main() style argv. Initial components are already
306  *              stripped.
307  *
308  * @return Normal NTSTATUS return.
309  **/
310
311 static NTSTATUS rpc_oldjoin_internals(struct net_context *c,
312                                         const DOM_SID *domain_sid,
313                                         const char *domain_name,
314                                         struct cli_state *cli,
315                                         struct rpc_pipe_client *pipe_hnd,
316                                         TALLOC_CTX *mem_ctx,
317                                         int argc,
318                                         const char **argv)
319 {
320
321         fstring trust_passwd;
322         unsigned char orig_trust_passwd_hash[16];
323         NTSTATUS result;
324         enum netr_SchannelType sec_channel_type;
325
326         result = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon.syntax_id,
327                                           &pipe_hnd);
328         if (!NT_STATUS_IS_OK(result)) {
329                 DEBUG(0,("rpc_oldjoin_internals: netlogon pipe open to machine %s failed. "
330                         "error was %s\n",
331                         cli->desthost,
332                         nt_errstr(result) ));
333                 return result;
334         }
335
336         /*
337            check what type of join - if the user want's to join as
338            a BDC, the server must agree that we are a BDC.
339         */
340         if (argc >= 0) {
341                 sec_channel_type = get_sec_channel_type(argv[0]);
342         } else {
343                 sec_channel_type = get_sec_channel_type(NULL);
344         }
345
346         fstrcpy(trust_passwd, global_myname());
347         strlower_m(trust_passwd);
348
349         /*
350          * Machine names can be 15 characters, but the max length on
351          * a password is 14.  --jerry
352          */
353
354         trust_passwd[14] = '\0';
355
356         E_md4hash(trust_passwd, orig_trust_passwd_hash);
357
358         result = trust_pw_change_and_store_it(pipe_hnd, mem_ctx, c->opt_target_workgroup,
359                                               global_myname(),
360                                               orig_trust_passwd_hash,
361                                               sec_channel_type);
362
363         if (NT_STATUS_IS_OK(result))
364                 printf(_("Joined domain %s.\n"), c->opt_target_workgroup);
365
366
367         if (!secrets_store_domain_sid(c->opt_target_workgroup, domain_sid)) {
368                 DEBUG(0, ("error storing domain sid for %s\n", c->opt_target_workgroup));
369                 result = NT_STATUS_UNSUCCESSFUL;
370         }
371
372         return result;
373 }
374
375 /**
376  * Join a domain, the old way.
377  *
378  * @param argc  Standard main() style argc.
379  * @param argv  Standard main() style argv. Initial components are already
380  *              stripped.
381  *
382  * @return A shell status integer (0 for success).
383  **/
384
385 static int net_rpc_perform_oldjoin(struct net_context *c, int argc, const char **argv)
386 {
387         return run_rpc_command(c, NULL, &ndr_table_netlogon.syntax_id,
388                                NET_FLAGS_NO_PIPE | NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC,
389                                rpc_oldjoin_internals,
390                                argc, argv);
391 }
392
393 /**
394  * Join a domain, the old way.  This function exists to allow
395  * the message to be displayed when oldjoin was explicitly
396  * requested, but not when it was implied by "net rpc join".
397  *
398  * @param argc  Standard main() style argc.
399  * @param argv  Standard main() style argv. Initial components are already
400  *              stripped.
401  *
402  * @return A shell status integer (0 for success).
403  **/
404
405 static int net_rpc_oldjoin(struct net_context *c, int argc, const char **argv)
406 {
407         int rc = -1;
408
409         if (c->display_usage) {
410                 d_printf(  "%s\n"
411                            "net rpc oldjoin\n"
412                            "    %s\n",
413                          _("Usage:"),
414                          _("Join a domain the old way"));
415                 return 0;
416         }
417
418         rc = net_rpc_perform_oldjoin(c, argc, argv);
419
420         if (rc) {
421                 d_fprintf(stderr, _("Failed to join domain\n"));
422         }
423
424         return rc;
425 }
426
427 /**
428  * 'net rpc join' entrypoint.
429  * @param argc  Standard main() style argc.
430  * @param argv  Standard main() style argv. Initial components are already
431  *              stripped
432  *
433  * Main 'net_rpc_join()' (where the admin username/password is used) is
434  * in net_rpc_join.c.
435  * Try to just change the password, but if that doesn't work, use/prompt
436  * for a username/password.
437  **/
438
439 int net_rpc_join(struct net_context *c, int argc, const char **argv)
440 {
441         if (c->display_usage) {
442                 d_printf("%s\n%s",
443                          _("Usage:"),
444                          _("net rpc join -U <username>[%%password] <type>\n"
445                            "  Join a domain\n"
446                            "    username\tName of the admin user"
447                            "    password\tPassword of the admin user, will "
448                            "prompt if not specified\n"
449                            "    type\tCan be one of the following:\n"
450                            "\t\tMEMBER\tJoin as member server (default)\n"
451                            "\t\tBDC\tJoin as BDC\n"
452                            "\t\tPDC\tJoin as PDC\n"));
453                 return 0;
454         }
455
456         if (lp_server_role() == ROLE_STANDALONE) {
457                 d_printf(_("cannot join as standalone machine\n"));
458                 return -1;
459         }
460
461         if (strlen(global_myname()) > 15) {
462                 d_printf(_("Our netbios name can be at most 15 chars long, "
463                            "\"%s\" is %u chars long\n"),
464                          global_myname(), (unsigned int)strlen(global_myname()));
465                 return -1;
466         }
467
468         if ((net_rpc_perform_oldjoin(c, argc, argv) == 0))
469                 return 0;
470
471         return net_rpc_join_newstyle(c, argc, argv);
472 }
473
474 /**
475  * display info about a rpc domain
476  *
477  * All parameters are provided by the run_rpc_command function, except for
478  * argc, argv which are passed through.
479  *
480  * @param domain_sid The domain sid acquired from the remote server
481  * @param cli A cli_state connected to the server.
482  * @param mem_ctx Talloc context, destroyed on completion of the function.
483  * @param argc  Standard main() style argc.
484  * @param argv  Standard main() style argv. Initial components are already
485  *              stripped.
486  *
487  * @return Normal NTSTATUS return.
488  **/
489
490 NTSTATUS rpc_info_internals(struct net_context *c,
491                         const DOM_SID *domain_sid,
492                         const char *domain_name,
493                         struct cli_state *cli,
494                         struct rpc_pipe_client *pipe_hnd,
495                         TALLOC_CTX *mem_ctx,
496                         int argc,
497                         const char **argv)
498 {
499         struct policy_handle connect_pol, domain_pol;
500         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
501         union samr_DomainInfo *info = NULL;
502         fstring sid_str;
503
504         sid_to_fstring(sid_str, domain_sid);
505
506         /* Get sam policy handle */
507         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
508                                       pipe_hnd->desthost,
509                                       MAXIMUM_ALLOWED_ACCESS,
510                                       &connect_pol);
511         if (!NT_STATUS_IS_OK(result)) {
512                 d_fprintf(stderr, _("Could not connect to SAM: %s\n"),
513                           nt_errstr(result));
514                 goto done;
515         }
516
517         /* Get domain policy handle */
518         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
519                                         &connect_pol,
520                                         MAXIMUM_ALLOWED_ACCESS,
521                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
522                                         &domain_pol);
523         if (!NT_STATUS_IS_OK(result)) {
524                 d_fprintf(stderr, _("Could not open domain: %s\n"),
525                           nt_errstr(result));
526                 goto done;
527         }
528
529         result = rpccli_samr_QueryDomainInfo(pipe_hnd, mem_ctx,
530                                              &domain_pol,
531                                              2,
532                                              &info);
533         if (NT_STATUS_IS_OK(result)) {
534                 d_printf(_("Domain Name: %s\n"),
535                          info->general.domain_name.string);
536                 d_printf(_("Domain SID: %s\n"), sid_str);
537                 d_printf(_("Sequence number: %llu\n"),
538                         (unsigned long long)info->general.sequence_num);
539                 d_printf(_("Num users: %u\n"), info->general.num_users);
540                 d_printf(_("Num domain groups: %u\n"),info->general.num_groups);
541                 d_printf(_("Num local groups: %u\n"),info->general.num_aliases);
542         }
543
544  done:
545         return result;
546 }
547
548 /**
549  * 'net rpc info' entrypoint.
550  * @param argc  Standard main() style argc.
551  * @param argv  Standard main() style argv. Initial components are already
552  *              stripped.
553  **/
554
555 int net_rpc_info(struct net_context *c, int argc, const char **argv)
556 {
557         if (c->display_usage) {
558                 d_printf(  "%s\n"
559                            "net rpc info\n"
560                            "  %s\n",
561                          _("Usage:"),
562                          _("Display information about the domain"));
563                 return 0;
564         }
565
566         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id,
567                                NET_FLAGS_PDC, rpc_info_internals,
568                                argc, argv);
569 }
570
571 /**
572  * Fetch domain SID into the local secrets.tdb.
573  *
574  * All parameters are provided by the run_rpc_command function, except for
575  * argc, argv which are passed through.
576  *
577  * @param domain_sid The domain sid acquired from the remote server.
578  * @param cli A cli_state connected to the server.
579  * @param mem_ctx Talloc context, destroyed on completion of the function.
580  * @param argc  Standard main() style argc.
581  * @param argv  Standard main() style argv. Initial components are already
582  *              stripped.
583  *
584  * @return Normal NTSTATUS return.
585  **/
586
587 static NTSTATUS rpc_getsid_internals(struct net_context *c,
588                         const DOM_SID *domain_sid,
589                         const char *domain_name,
590                         struct cli_state *cli,
591                         struct rpc_pipe_client *pipe_hnd,
592                         TALLOC_CTX *mem_ctx,
593                         int argc,
594                         const char **argv)
595 {
596         fstring sid_str;
597
598         sid_to_fstring(sid_str, domain_sid);
599         d_printf(_("Storing SID %s for Domain %s in secrets.tdb\n"),
600                  sid_str, domain_name);
601
602         if (!secrets_store_domain_sid(domain_name, domain_sid)) {
603                 DEBUG(0,("Can't store domain SID\n"));
604                 return NT_STATUS_UNSUCCESSFUL;
605         }
606
607         return NT_STATUS_OK;
608 }
609
610 /**
611  * 'net rpc getsid' entrypoint.
612  * @param argc  Standard main() style argc.
613  * @param argv  Standard main() style argv. Initial components are already
614  *              stripped.
615  **/
616
617 int net_rpc_getsid(struct net_context *c, int argc, const char **argv)
618 {
619         int conn_flags = NET_FLAGS_PDC;
620
621         if (!c->opt_user_specified) {
622                 conn_flags |= NET_FLAGS_ANONYMOUS;
623         }
624
625         if (c->display_usage) {
626                 d_printf(  "%s\n"
627                            "net rpc getsid\n"
628                            "    %s\n",
629                          _("Usage:"),
630                          _("Fetch domain SID into local secrets.tdb"));
631                 return 0;
632         }
633
634         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id,
635                                conn_flags,
636                                rpc_getsid_internals,
637                                argc, argv);
638 }
639
640 /****************************************************************************/
641
642 /**
643  * Basic usage function for 'net rpc user'.
644  * @param argc  Standard main() style argc.
645  * @param argv  Standard main() style argv. Initial components are already
646  *              stripped.
647  **/
648
649 static int rpc_user_usage(struct net_context *c, int argc, const char **argv)
650 {
651         return net_user_usage(c, argc, argv);
652 }
653
654 /**
655  * Add a new user to a remote RPC server.
656  *
657  * @param argc  Standard main() style argc.
658  * @param argv  Standard main() style argv. Initial components are already
659  *              stripped.
660  *
661  * @return A shell status integer (0 for success).
662  **/
663
664 static int rpc_user_add(struct net_context *c, int argc, const char **argv)
665 {
666         NET_API_STATUS status;
667         struct USER_INFO_1 info1;
668         uint32_t parm_error = 0;
669
670         if (argc < 1 || c->display_usage) {
671                 rpc_user_usage(c, argc, argv);
672                 return 0;
673         }
674
675         ZERO_STRUCT(info1);
676
677         info1.usri1_name = argv[0];
678         if (argc == 2) {
679                 info1.usri1_password = argv[1];
680         }
681
682         status = NetUserAdd(c->opt_host, 1, (uint8_t *)&info1, &parm_error);
683
684         if (status != 0) {
685                 d_fprintf(stderr,_("Failed to add user '%s' with error: %s.\n"),
686                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
687                                                             status));
688                 return -1;
689         } else {
690                 d_printf(_("Added user '%s'.\n"), argv[0]);
691         }
692
693         return 0;
694 }
695
696 /**
697  * Rename a user on a remote RPC server.
698  *
699  * @param argc  Standard main() style argc.
700  * @param argv  Standard main() style argv. Initial components are already
701  *              stripped.
702  *
703  * @return A shell status integer (0 for success).
704  **/
705
706 static int rpc_user_rename(struct net_context *c, int argc, const char **argv)
707 {
708         NET_API_STATUS status;
709         struct USER_INFO_0 u0;
710         uint32_t parm_err = 0;
711
712         if (argc != 2 || c->display_usage) {
713                 rpc_user_usage(c, argc, argv);
714                 return 0;
715         }
716
717         u0.usri0_name = argv[1];
718
719         status = NetUserSetInfo(c->opt_host, argv[0],
720                                 0, (uint8_t *)&u0, &parm_err);
721         if (status) {
722                 d_fprintf(stderr,
723                           _("Failed to rename user from %s to %s - %s\n"),
724                           argv[0], argv[1],
725                           libnetapi_get_error_string(c->netapi_ctx, status));
726         } else {
727                 d_printf(_("Renamed user from %s to %s\n"), argv[0], argv[1]);
728         }
729
730         return status;
731 }
732
733 /**
734  * Delete a user from a remote RPC server.
735  *
736  * @param argc  Standard main() style argc.
737  * @param argv  Standard main() style argv. Initial components are already
738  *              stripped.
739  *
740  * @return A shell status integer (0 for success).
741  **/
742
743 static int rpc_user_delete(struct net_context *c, int argc, const char **argv)
744 {
745         NET_API_STATUS status;
746
747         if (argc < 1 || c->display_usage) {
748                 rpc_user_usage(c, argc, argv);
749                 return 0;
750         }
751
752         status = NetUserDel(c->opt_host, argv[0]);
753
754         if (status != 0) {
755                 d_fprintf(stderr, _("Failed to delete user '%s' with: %s.\n"),
756                           argv[0],
757                           libnetapi_get_error_string(c->netapi_ctx, status));
758                 return -1;
759         } else {
760                 d_printf(_("Deleted user '%s'.\n"), argv[0]);
761         }
762
763         return 0;
764 }
765
766 /**
767  * Set a user's password on a remote RPC server.
768  *
769  * @param argc  Standard main() style argc.
770  * @param argv  Standard main() style argv. Initial components are already
771  *              stripped.
772  *
773  * @return A shell status integer (0 for success).
774  **/
775
776 static int rpc_user_password(struct net_context *c, int argc, const char **argv)
777 {
778         NET_API_STATUS status;
779         char *prompt = NULL;
780         struct USER_INFO_1003 u1003;
781         uint32_t parm_err = 0;
782         int ret;
783
784         if (argc < 1 || c->display_usage) {
785                 rpc_user_usage(c, argc, argv);
786                 return 0;
787         }
788
789         if (argv[1]) {
790                 u1003.usri1003_password = argv[1];
791         } else {
792                 ret = asprintf(&prompt, _("Enter new password for %s:"),
793                                argv[0]);
794                 if (ret == -1) {
795                         return -1;
796                 }
797                 u1003.usri1003_password = getpass(prompt);
798                 SAFE_FREE(prompt);
799         }
800
801         status = NetUserSetInfo(c->opt_host, argv[0], 1003, (uint8_t *)&u1003, &parm_err);
802
803         /* Display results */
804         if (status != 0) {
805                 d_fprintf(stderr,
806                         _("Failed to set password for '%s' with error: %s.\n"),
807                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
808                                                             status));
809                 return -1;
810         }
811
812         return 0;
813 }
814
815 /**
816  * List a user's groups from a remote RPC server.
817  *
818  * @param argc  Standard main() style argc.
819  * @param argv  Standard main() style argv. Initial components are already
820  *              stripped.
821  *
822  * @return A shell status integer (0 for success)
823  **/
824
825 static int rpc_user_info(struct net_context *c, int argc, const char **argv)
826
827 {
828         NET_API_STATUS status;
829         struct GROUP_USERS_INFO_0 *u0 = NULL;
830         uint32_t entries_read = 0;
831         uint32_t total_entries = 0;
832         int i;
833
834
835         if (argc < 1 || c->display_usage) {
836                 rpc_user_usage(c, argc, argv);
837                 return 0;
838         }
839
840         status = NetUserGetGroups(c->opt_host,
841                                   argv[0],
842                                   0,
843                                   (uint8_t **)(void *)&u0,
844                                   (uint32_t)-1,
845                                   &entries_read,
846                                   &total_entries);
847         if (status != 0) {
848                 d_fprintf(stderr,
849                         _("Failed to get groups for '%s' with error: %s.\n"),
850                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
851                                                             status));
852                 return -1;
853         }
854
855         for (i=0; i < entries_read; i++) {
856                 printf("%s\n", u0->grui0_name);
857                 u0++;
858         }
859
860         return 0;
861 }
862
863 /**
864  * List users on a remote RPC server.
865  *
866  * All parameters are provided by the run_rpc_command function, except for
867  * argc, argv which are passed through.
868  *
869  * @param domain_sid The domain sid acquired from the remote server.
870  * @param cli A cli_state connected to the server.
871  * @param mem_ctx Talloc context, destroyed on completion of the function.
872  * @param argc  Standard main() style argc.
873  * @param argv  Standard main() style argv. Initial components are already
874  *              stripped.
875  *
876  * @return Normal NTSTATUS return.
877  **/
878
879 static int rpc_user_list(struct net_context *c, int argc, const char **argv)
880 {
881         NET_API_STATUS status;
882         uint32_t start_idx=0, num_entries, i, loop_count = 0;
883         struct NET_DISPLAY_USER *info = NULL;
884         void *buffer = NULL;
885
886         /* Query domain users */
887         if (c->opt_long_list_entries)
888                 d_printf(_("\nUser name             Comment"
889                            "\n-----------------------------\n"));
890         do {
891                 uint32_t max_entries, max_size;
892
893                 get_query_dispinfo_params(
894                         loop_count, &max_entries, &max_size);
895
896                 status = NetQueryDisplayInformation(c->opt_host,
897                                                     1,
898                                                     start_idx,
899                                                     max_entries,
900                                                     max_size,
901                                                     &num_entries,
902                                                     &buffer);
903                 if (status != 0 && status != ERROR_MORE_DATA) {
904                         return status;
905                 }
906
907                 info = (struct NET_DISPLAY_USER *)buffer;
908
909                 for (i = 0; i < num_entries; i++) {
910
911                         if (c->opt_long_list_entries)
912                                 printf("%-21.21s %s\n", info->usri1_name,
913                                         info->usri1_comment);
914                         else
915                                 printf("%s\n", info->usri1_name);
916                         info++;
917                 }
918
919                 NetApiBufferFree(buffer);
920
921                 loop_count++;
922                 start_idx += num_entries;
923
924         } while (status == ERROR_MORE_DATA);
925
926         return status;
927 }
928
929 /**
930  * 'net rpc user' entrypoint.
931  * @param argc  Standard main() style argc.
932  * @param argv  Standard main() style argv. Initial components are already
933  *              stripped.
934  **/
935
936 int net_rpc_user(struct net_context *c, int argc, const char **argv)
937 {
938         NET_API_STATUS status;
939
940         struct functable func[] = {
941                 {
942                         "add",
943                         rpc_user_add,
944                         NET_TRANSPORT_RPC,
945                         N_("Add specified user"),
946                         N_("net rpc user add\n"
947                            "    Add specified user")
948                 },
949                 {
950                         "info",
951                         rpc_user_info,
952                         NET_TRANSPORT_RPC,
953                         N_("List domain groups of user"),
954                         N_("net rpc user info\n"
955                            "    Lis domain groups of user")
956                 },
957                 {
958                         "delete",
959                         rpc_user_delete,
960                         NET_TRANSPORT_RPC,
961                         N_("Remove specified user"),
962                         N_("net rpc user delete\n"
963                            "    Remove specified user")
964                 },
965                 {
966                         "password",
967                         rpc_user_password,
968                         NET_TRANSPORT_RPC,
969                         N_("Change user password"),
970                         N_("net rpc user password\n"
971                            "    Change user password")
972                 },
973                 {
974                         "rename",
975                         rpc_user_rename,
976                         NET_TRANSPORT_RPC,
977                         N_("Rename specified user"),
978                         N_("net rpc user rename\n"
979                            "    Rename specified user")
980                 },
981                 {NULL, NULL, 0, NULL, NULL}
982         };
983
984         status = libnetapi_init(&c->netapi_ctx);
985         if (status != 0) {
986                 return -1;
987         }
988         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
989         libnetapi_set_password(c->netapi_ctx, c->opt_password);
990         if (c->opt_kerberos) {
991                 libnetapi_set_use_kerberos(c->netapi_ctx);
992         }
993
994         if (argc == 0) {
995                 if (c->display_usage) {
996                         d_printf(  "%s\n"
997                                    "net rpc user\n"
998                                    "    %s\n",
999                                  _("Usage:"),
1000                                  _("List all users"));
1001                         net_display_usage_from_functable(func);
1002                         return 0;
1003                 }
1004
1005                 return rpc_user_list(c, argc, argv);
1006         }
1007
1008         return net_run_function(c, argc, argv, "net rpc user", func);
1009 }
1010
1011 static NTSTATUS rpc_sh_user_list(struct net_context *c,
1012                                  TALLOC_CTX *mem_ctx,
1013                                  struct rpc_sh_ctx *ctx,
1014                                  struct rpc_pipe_client *pipe_hnd,
1015                                  int argc, const char **argv)
1016 {
1017         return werror_to_ntstatus(W_ERROR(rpc_user_list(c, argc, argv)));
1018 }
1019
1020 static NTSTATUS rpc_sh_user_info(struct net_context *c,
1021                                  TALLOC_CTX *mem_ctx,
1022                                  struct rpc_sh_ctx *ctx,
1023                                  struct rpc_pipe_client *pipe_hnd,
1024                                  int argc, const char **argv)
1025 {
1026         return werror_to_ntstatus(W_ERROR(rpc_user_info(c, argc, argv)));
1027 }
1028
1029 static NTSTATUS rpc_sh_handle_user(struct net_context *c,
1030                                    TALLOC_CTX *mem_ctx,
1031                                    struct rpc_sh_ctx *ctx,
1032                                    struct rpc_pipe_client *pipe_hnd,
1033                                    int argc, const char **argv,
1034                                    NTSTATUS (*fn)(
1035                                            struct net_context *c,
1036                                            TALLOC_CTX *mem_ctx,
1037                                            struct rpc_sh_ctx *ctx,
1038                                            struct rpc_pipe_client *pipe_hnd,
1039                                            struct policy_handle *user_hnd,
1040                                            int argc, const char **argv))
1041 {
1042         struct policy_handle connect_pol, domain_pol, user_pol;
1043         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1044         DOM_SID sid;
1045         uint32 rid;
1046         enum lsa_SidType type;
1047
1048         if (argc == 0) {
1049                 d_fprintf(stderr, "%s %s <username>\n", _("Usage:"),
1050                           ctx->whoami);
1051                 return NT_STATUS_INVALID_PARAMETER;
1052         }
1053
1054         ZERO_STRUCT(connect_pol);
1055         ZERO_STRUCT(domain_pol);
1056         ZERO_STRUCT(user_pol);
1057
1058         result = net_rpc_lookup_name(c, mem_ctx, rpc_pipe_np_smb_conn(pipe_hnd),
1059                                      argv[0], NULL, NULL, &sid, &type);
1060         if (!NT_STATUS_IS_OK(result)) {
1061                 d_fprintf(stderr, _("Could not lookup %s: %s\n"), argv[0],
1062                           nt_errstr(result));
1063                 goto done;
1064         }
1065
1066         if (type != SID_NAME_USER) {
1067                 d_fprintf(stderr, _("%s is a %s, not a user\n"), argv[0],
1068                           sid_type_lookup(type));
1069                 result = NT_STATUS_NO_SUCH_USER;
1070                 goto done;
1071         }
1072
1073         if (!sid_peek_check_rid(ctx->domain_sid, &sid, &rid)) {
1074                 d_fprintf(stderr, _("%s is not in our domain\n"), argv[0]);
1075                 result = NT_STATUS_NO_SUCH_USER;
1076                 goto done;
1077         }
1078
1079         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
1080                                       pipe_hnd->desthost,
1081                                       MAXIMUM_ALLOWED_ACCESS,
1082                                       &connect_pol);
1083         if (!NT_STATUS_IS_OK(result)) {
1084                 goto done;
1085         }
1086
1087         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
1088                                         &connect_pol,
1089                                         MAXIMUM_ALLOWED_ACCESS,
1090                                         ctx->domain_sid,
1091                                         &domain_pol);
1092         if (!NT_STATUS_IS_OK(result)) {
1093                 goto done;
1094         }
1095
1096         result = rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
1097                                       &domain_pol,
1098                                       MAXIMUM_ALLOWED_ACCESS,
1099                                       rid,
1100                                       &user_pol);
1101         if (!NT_STATUS_IS_OK(result)) {
1102                 goto done;
1103         }
1104
1105         result = fn(c, mem_ctx, ctx, pipe_hnd, &user_pol, argc-1, argv+1);
1106
1107  done:
1108         if (is_valid_policy_hnd(&user_pol)) {
1109                 rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1110         }
1111         if (is_valid_policy_hnd(&domain_pol)) {
1112                 rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_pol);
1113         }
1114         if (is_valid_policy_hnd(&connect_pol)) {
1115                 rpccli_samr_Close(pipe_hnd, mem_ctx, &connect_pol);
1116         }
1117         return result;
1118 }
1119
1120 static NTSTATUS rpc_sh_user_show_internals(struct net_context *c,
1121                                            TALLOC_CTX *mem_ctx,
1122                                            struct rpc_sh_ctx *ctx,
1123                                            struct rpc_pipe_client *pipe_hnd,
1124                                            struct policy_handle *user_hnd,
1125                                            int argc, const char **argv)
1126 {
1127         NTSTATUS result;
1128         union samr_UserInfo *info = NULL;
1129
1130         if (argc != 0) {
1131                 d_fprintf(stderr, "%s %s show <username>\n", _("Usage:"),
1132                           ctx->whoami);
1133                 return NT_STATUS_INVALID_PARAMETER;
1134         }
1135
1136         result = rpccli_samr_QueryUserInfo(pipe_hnd, mem_ctx,
1137                                            user_hnd,
1138                                            21,
1139                                            &info);
1140         if (!NT_STATUS_IS_OK(result)) {
1141                 return result;
1142         }
1143
1144         d_printf(_("user rid: %d, group rid: %d\n"),
1145                 info->info21.rid,
1146                 info->info21.primary_gid);
1147
1148         return result;
1149 }
1150
1151 static NTSTATUS rpc_sh_user_show(struct net_context *c,
1152                                  TALLOC_CTX *mem_ctx,
1153                                  struct rpc_sh_ctx *ctx,
1154                                  struct rpc_pipe_client *pipe_hnd,
1155                                  int argc, const char **argv)
1156 {
1157         return rpc_sh_handle_user(c, mem_ctx, ctx, pipe_hnd, argc, argv,
1158                                   rpc_sh_user_show_internals);
1159 }
1160
1161 #define FETCHSTR(name, rec) \
1162 do { if (strequal(ctx->thiscmd, name)) { \
1163         oldval = talloc_strdup(mem_ctx, info->info21.rec.string); } \
1164 } while (0);
1165
1166 #define SETSTR(name, rec, flag) \
1167 do { if (strequal(ctx->thiscmd, name)) { \
1168         init_lsa_String(&(info->info21.rec), argv[0]); \
1169         info->info21.fields_present |= SAMR_FIELD_##flag; } \
1170 } while (0);
1171
1172 static NTSTATUS rpc_sh_user_str_edit_internals(struct net_context *c,
1173                                                TALLOC_CTX *mem_ctx,
1174                                                struct rpc_sh_ctx *ctx,
1175                                                struct rpc_pipe_client *pipe_hnd,
1176                                                struct policy_handle *user_hnd,
1177                                                int argc, const char **argv)
1178 {
1179         NTSTATUS result;
1180         const char *username;
1181         const char *oldval = "";
1182         union samr_UserInfo *info = NULL;
1183
1184         if (argc > 1) {
1185                 d_fprintf(stderr, "%s %s <username> [new value|NULL]\n",
1186                           _("Usage:"), ctx->whoami);
1187                 return NT_STATUS_INVALID_PARAMETER;
1188         }
1189
1190         result = rpccli_samr_QueryUserInfo(pipe_hnd, mem_ctx,
1191                                            user_hnd,
1192                                            21,
1193                                            &info);
1194         if (!NT_STATUS_IS_OK(result)) {
1195                 return result;
1196         }
1197
1198         username = talloc_strdup(mem_ctx, info->info21.account_name.string);
1199
1200         FETCHSTR("fullname", full_name);
1201         FETCHSTR("homedir", home_directory);
1202         FETCHSTR("homedrive", home_drive);
1203         FETCHSTR("logonscript", logon_script);
1204         FETCHSTR("profilepath", profile_path);
1205         FETCHSTR("description", description);
1206
1207         if (argc == 0) {
1208                 d_printf(_("%s's %s: [%s]\n"), username, ctx->thiscmd, oldval);
1209                 goto done;
1210         }
1211
1212         if (strcmp(argv[0], "NULL") == 0) {
1213                 argv[0] = "";
1214         }
1215
1216         ZERO_STRUCT(info->info21);
1217
1218         SETSTR("fullname", full_name, FULL_NAME);
1219         SETSTR("homedir", home_directory, HOME_DIRECTORY);
1220         SETSTR("homedrive", home_drive, HOME_DRIVE);
1221         SETSTR("logonscript", logon_script, LOGON_SCRIPT);
1222         SETSTR("profilepath", profile_path, PROFILE_PATH);
1223         SETSTR("description", description, DESCRIPTION);
1224
1225         result = rpccli_samr_SetUserInfo(pipe_hnd, mem_ctx,
1226                                          user_hnd,
1227                                          21,
1228                                          info);
1229
1230         d_printf(_("Set %s's %s from [%s] to [%s]\n"), username,
1231                  ctx->thiscmd, oldval, argv[0]);
1232
1233  done:
1234
1235         return result;
1236 }
1237
1238 #define HANDLEFLG(name, rec) \
1239 do { if (strequal(ctx->thiscmd, name)) { \
1240         oldval = (oldflags & ACB_##rec) ? "yes" : "no"; \
1241         if (newval) { \
1242                 newflags = oldflags | ACB_##rec; \
1243         } else { \
1244                 newflags = oldflags & ~ACB_##rec; \
1245         } } } while (0);
1246
1247 static NTSTATUS rpc_sh_user_str_edit(struct net_context *c,
1248                                      TALLOC_CTX *mem_ctx,
1249                                      struct rpc_sh_ctx *ctx,
1250                                      struct rpc_pipe_client *pipe_hnd,
1251                                      int argc, const char **argv)
1252 {
1253         return rpc_sh_handle_user(c, mem_ctx, ctx, pipe_hnd, argc, argv,
1254                                   rpc_sh_user_str_edit_internals);
1255 }
1256
1257 static NTSTATUS rpc_sh_user_flag_edit_internals(struct net_context *c,
1258                                                 TALLOC_CTX *mem_ctx,
1259                                                 struct rpc_sh_ctx *ctx,
1260                                                 struct rpc_pipe_client *pipe_hnd,
1261                                                 struct policy_handle *user_hnd,
1262                                                 int argc, const char **argv)
1263 {
1264         NTSTATUS result;
1265         const char *username;
1266         const char *oldval = "unknown";
1267         uint32 oldflags, newflags;
1268         bool newval;
1269         union samr_UserInfo *info = NULL;
1270
1271         if ((argc > 1) ||
1272             ((argc == 1) && !strequal(argv[0], "yes") &&
1273              !strequal(argv[0], "no"))) {
1274                 /* TRANSATORS: The yes|no here are program keywords. Please do
1275                    not translate. */
1276                 d_fprintf(stderr, _("Usage: %s <username> [yes|no]\n"),
1277                           ctx->whoami);
1278                 return NT_STATUS_INVALID_PARAMETER;
1279         }
1280
1281         newval = strequal(argv[0], "yes");
1282
1283         result = rpccli_samr_QueryUserInfo(pipe_hnd, mem_ctx,
1284                                            user_hnd,
1285                                            21,
1286                                            &info);
1287         if (!NT_STATUS_IS_OK(result)) {
1288                 return result;
1289         }
1290
1291         username = talloc_strdup(mem_ctx, info->info21.account_name.string);
1292         oldflags = info->info21.acct_flags;
1293         newflags = info->info21.acct_flags;
1294
1295         HANDLEFLG("disabled", DISABLED);
1296         HANDLEFLG("pwnotreq", PWNOTREQ);
1297         HANDLEFLG("autolock", AUTOLOCK);
1298         HANDLEFLG("pwnoexp", PWNOEXP);
1299
1300         if (argc == 0) {
1301                 d_printf(_("%s's %s flag: %s\n"), username, ctx->thiscmd,
1302                          oldval);
1303                 goto done;
1304         }
1305
1306         ZERO_STRUCT(info->info21);
1307
1308         info->info21.acct_flags = newflags;
1309         info->info21.fields_present = SAMR_FIELD_ACCT_FLAGS;
1310
1311         result = rpccli_samr_SetUserInfo(pipe_hnd, mem_ctx,
1312                                          user_hnd,
1313                                          21,
1314                                          info);
1315
1316         if (NT_STATUS_IS_OK(result)) {
1317                 d_printf(_("Set %s's %s flag from [%s] to [%s]\n"), username,
1318                          ctx->thiscmd, oldval, argv[0]);
1319         }
1320
1321  done:
1322
1323         return result;
1324 }
1325
1326 static NTSTATUS rpc_sh_user_flag_edit(struct net_context *c,
1327                                       TALLOC_CTX *mem_ctx,
1328                                       struct rpc_sh_ctx *ctx,
1329                                       struct rpc_pipe_client *pipe_hnd,
1330                                       int argc, const char **argv)
1331 {
1332         return rpc_sh_handle_user(c, mem_ctx, ctx, pipe_hnd, argc, argv,
1333                                   rpc_sh_user_flag_edit_internals);
1334 }
1335
1336 struct rpc_sh_cmd *net_rpc_user_edit_cmds(struct net_context *c,
1337                                           TALLOC_CTX *mem_ctx,
1338                                           struct rpc_sh_ctx *ctx)
1339 {
1340         static struct rpc_sh_cmd cmds[] = {
1341
1342                 { "fullname", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
1343                   N_("Show/Set a user's full name") },
1344
1345                 { "homedir", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
1346                   N_("Show/Set a user's home directory") },
1347
1348                 { "homedrive", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
1349                   N_("Show/Set a user's home drive") },
1350
1351                 { "logonscript", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
1352                   N_("Show/Set a user's logon script") },
1353
1354                 { "profilepath", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
1355                   N_("Show/Set a user's profile path") },
1356
1357                 { "description", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_str_edit,
1358                   N_("Show/Set a user's description") },
1359
1360                 { "disabled", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_flag_edit,
1361                   N_("Show/Set whether a user is disabled") },
1362
1363                 { "autolock", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_flag_edit,
1364                   N_("Show/Set whether a user locked out") },
1365
1366                 { "pwnotreq", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_flag_edit,
1367                   N_("Show/Set whether a user does not need a password") },
1368
1369                 { "pwnoexp", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_flag_edit,
1370                   N_("Show/Set whether a user's password does not expire") },
1371
1372                 { NULL, NULL, 0, NULL, NULL }
1373         };
1374
1375         return cmds;
1376 }
1377
1378 struct rpc_sh_cmd *net_rpc_user_cmds(struct net_context *c,
1379                                      TALLOC_CTX *mem_ctx,
1380                                      struct rpc_sh_ctx *ctx)
1381 {
1382         static struct rpc_sh_cmd cmds[] = {
1383
1384                 { "list", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_list,
1385                   N_("List available users") },
1386
1387                 { "info", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_info,
1388                   N_("List the domain groups a user is member of") },
1389
1390                 { "show", NULL, &ndr_table_samr.syntax_id, rpc_sh_user_show,
1391                   N_("Show info about a user") },
1392
1393                 { "edit", net_rpc_user_edit_cmds, 0, NULL,
1394                   N_("Show/Modify a user's fields") },
1395
1396                 { NULL, NULL, 0, NULL, NULL }
1397         };
1398
1399         return cmds;
1400 }
1401
1402 /****************************************************************************/
1403
1404 /**
1405  * Basic usage function for 'net rpc group'.
1406  * @param argc  Standard main() style argc.
1407  * @param argv  Standard main() style argv. Initial components are already
1408  *              stripped.
1409  **/
1410
1411 static int rpc_group_usage(struct net_context *c, int argc, const char **argv)
1412 {
1413         return net_group_usage(c, argc, argv);
1414 }
1415
1416 /**
1417  * Delete group on a remote RPC server.
1418  *
1419  * All parameters are provided by the run_rpc_command function, except for
1420  * argc, argv which are passed through.
1421  *
1422  * @param domain_sid The domain sid acquired from the remote server.
1423  * @param cli A cli_state connected to the server.
1424  * @param mem_ctx Talloc context, destroyed on completion of the function.
1425  * @param argc  Standard main() style argc.
1426  * @param argv  Standard main() style argv. Initial components are already
1427  *              stripped.
1428  *
1429  * @return Normal NTSTATUS return.
1430  **/
1431
1432 static NTSTATUS rpc_group_delete_internals(struct net_context *c,
1433                                         const DOM_SID *domain_sid,
1434                                         const char *domain_name,
1435                                         struct cli_state *cli,
1436                                         struct rpc_pipe_client *pipe_hnd,
1437                                         TALLOC_CTX *mem_ctx,
1438                                         int argc,
1439                                         const char **argv)
1440 {
1441         struct policy_handle connect_pol, domain_pol, group_pol, user_pol;
1442         bool group_is_primary = false;
1443         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1444         uint32_t group_rid;
1445         struct samr_RidTypeArray *rids = NULL;
1446         /* char **names; */
1447         int i;
1448         /* struct samr_RidWithAttribute *user_gids; */
1449
1450         struct samr_Ids group_rids, name_types;
1451         struct lsa_String lsa_acct_name;
1452         union samr_UserInfo *info = NULL;
1453
1454         if (argc < 1 || c->display_usage) {
1455                 rpc_group_usage(c, argc,argv);
1456                 return NT_STATUS_OK; /* ok? */
1457         }
1458
1459         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
1460                                       pipe_hnd->desthost,
1461                                       MAXIMUM_ALLOWED_ACCESS,
1462                                       &connect_pol);
1463
1464         if (!NT_STATUS_IS_OK(result)) {
1465                 d_fprintf(stderr, _("Request samr_Connect2 failed\n"));
1466                 goto done;
1467         }
1468
1469         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
1470                                         &connect_pol,
1471                                         MAXIMUM_ALLOWED_ACCESS,
1472                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
1473                                         &domain_pol);
1474
1475         if (!NT_STATUS_IS_OK(result)) {
1476                 d_fprintf(stderr, _("Request open_domain failed\n"));
1477                 goto done;
1478         }
1479
1480         init_lsa_String(&lsa_acct_name, argv[0]);
1481
1482         result = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
1483                                          &domain_pol,
1484                                          1,
1485                                          &lsa_acct_name,
1486                                          &group_rids,
1487                                          &name_types);
1488         if (!NT_STATUS_IS_OK(result)) {
1489                 d_fprintf(stderr, _("Lookup of '%s' failed\n"),argv[0]);
1490                 goto done;
1491         }
1492
1493         switch (name_types.ids[0])
1494         {
1495         case SID_NAME_DOM_GRP:
1496                 result = rpccli_samr_OpenGroup(pipe_hnd, mem_ctx,
1497                                                &domain_pol,
1498                                                MAXIMUM_ALLOWED_ACCESS,
1499                                                group_rids.ids[0],
1500                                                &group_pol);
1501                 if (!NT_STATUS_IS_OK(result)) {
1502                         d_fprintf(stderr, _("Request open_group failed"));
1503                         goto done;
1504                 }
1505
1506                 group_rid = group_rids.ids[0];
1507
1508                 result = rpccli_samr_QueryGroupMember(pipe_hnd, mem_ctx,
1509                                                       &group_pol,
1510                                                       &rids);
1511
1512                 if (!NT_STATUS_IS_OK(result)) {
1513                         d_fprintf(stderr,
1514                                   _("Unable to query group members of %s"),
1515                                   argv[0]);
1516                         goto done;
1517                 }
1518
1519                 if (c->opt_verbose) {
1520                         d_printf(
1521                                 _("Domain Group %s (rid: %d) has %d members\n"),
1522                                 argv[0],group_rid, rids->count);
1523                 }
1524
1525                 /* Check if group is anyone's primary group */
1526                 for (i = 0; i < rids->count; i++)
1527                 {
1528                         result = rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
1529                                                       &domain_pol,
1530                                                       MAXIMUM_ALLOWED_ACCESS,
1531                                                       rids->rids[i],
1532                                                       &user_pol);
1533
1534                         if (!NT_STATUS_IS_OK(result)) {
1535                                 d_fprintf(stderr,
1536                                         _("Unable to open group member %d\n"),
1537                                         rids->rids[i]);
1538                                 goto done;
1539                         }
1540
1541                         result = rpccli_samr_QueryUserInfo(pipe_hnd, mem_ctx,
1542                                                            &user_pol,
1543                                                            21,
1544                                                            &info);
1545
1546                         if (!NT_STATUS_IS_OK(result)) {
1547                                 d_fprintf(stderr,
1548                                         _("Unable to lookup userinfo for group "
1549                                           "member %d\n"),
1550                                         rids->rids[i]);
1551                                 goto done;
1552                         }
1553
1554                         if (info->info21.primary_gid == group_rid) {
1555                                 if (c->opt_verbose) {
1556                                         d_printf(_("Group is primary group "
1557                                                    "of %s\n"),
1558                                                 info->info21.account_name.string);
1559                                 }
1560                                 group_is_primary = true;
1561                         }
1562
1563                         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1564                 }
1565
1566                 if (group_is_primary) {
1567                         d_fprintf(stderr, _("Unable to delete group because "
1568                                  "some of it's members have it as primary "
1569                                  "group\n"));
1570                         result = NT_STATUS_MEMBERS_PRIMARY_GROUP;
1571                         goto done;
1572                 }
1573
1574                 /* remove all group members */
1575                 for (i = 0; i < rids->count; i++)
1576                 {
1577                         if (c->opt_verbose)
1578                                 d_printf(_("Remove group member %d..."),
1579                                         rids->rids[i]);
1580                         result = rpccli_samr_DeleteGroupMember(pipe_hnd, mem_ctx,
1581                                                                &group_pol,
1582                                                                rids->rids[i]);
1583
1584                         if (NT_STATUS_IS_OK(result)) {
1585                                 if (c->opt_verbose)
1586                                         d_printf(_("ok\n"));
1587                         } else {
1588                                 if (c->opt_verbose)
1589                                         d_printf("%s\n", _("failed"));
1590                                 goto done;
1591                         }
1592                 }
1593
1594                 result = rpccli_samr_DeleteDomainGroup(pipe_hnd, mem_ctx,
1595                                                        &group_pol);
1596
1597                 break;
1598         /* removing a local group is easier... */
1599         case SID_NAME_ALIAS:
1600                 result = rpccli_samr_OpenAlias(pipe_hnd, mem_ctx,
1601                                                &domain_pol,
1602                                                MAXIMUM_ALLOWED_ACCESS,
1603                                                group_rids.ids[0],
1604                                                &group_pol);
1605
1606                 if (!NT_STATUS_IS_OK(result)) {
1607                         d_fprintf(stderr, _("Request open_alias failed\n"));
1608                         goto done;
1609                 }
1610
1611                 result = rpccli_samr_DeleteDomAlias(pipe_hnd, mem_ctx,
1612                                                     &group_pol);
1613                 break;
1614         default:
1615                 d_fprintf(stderr, _("%s is of type %s. This command is only "
1616                                     "for deleting local or global groups\n"),
1617                         argv[0],sid_type_lookup(name_types.ids[0]));
1618                 result = NT_STATUS_UNSUCCESSFUL;
1619                 goto done;
1620         }
1621
1622         if (NT_STATUS_IS_OK(result)) {
1623                 if (c->opt_verbose)
1624                         d_printf(_("Deleted %s '%s'\n"),
1625                                  sid_type_lookup(name_types.ids[0]), argv[0]);
1626         } else {
1627                 d_fprintf(stderr, _("Deleting of %s failed: %s\n"), argv[0],
1628                         get_friendly_nt_error_msg(result));
1629         }
1630
1631  done:
1632         return result;
1633
1634 }
1635
1636 static int rpc_group_delete(struct net_context *c, int argc, const char **argv)
1637 {
1638         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
1639                                rpc_group_delete_internals, argc,argv);
1640 }
1641
1642 static int rpc_group_add_internals(struct net_context *c, int argc, const char **argv)
1643 {
1644         NET_API_STATUS status;
1645         struct GROUP_INFO_1 info1;
1646         uint32_t parm_error = 0;
1647
1648         if (argc != 1 || c->display_usage) {
1649                 rpc_group_usage(c, argc, argv);
1650                 return 0;
1651         }
1652
1653         ZERO_STRUCT(info1);
1654
1655         info1.grpi1_name = argv[0];
1656         if (c->opt_comment && strlen(c->opt_comment) > 0) {
1657                 info1.grpi1_comment = c->opt_comment;
1658         }
1659
1660         status = NetGroupAdd(c->opt_host, 1, (uint8_t *)&info1, &parm_error);
1661
1662         if (status != 0) {
1663                 d_fprintf(stderr,
1664                         _("Failed to add group '%s' with error: %s.\n"),
1665                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
1666                                                             status));
1667                 return -1;
1668         } else {
1669                 d_printf(_("Added group '%s'.\n"), argv[0]);
1670         }
1671
1672         return 0;
1673 }
1674
1675 static int rpc_alias_add_internals(struct net_context *c, int argc, const char **argv)
1676 {
1677         NET_API_STATUS status;
1678         struct LOCALGROUP_INFO_1 info1;
1679         uint32_t parm_error = 0;
1680
1681         if (argc != 1 || c->display_usage) {
1682                 rpc_group_usage(c, argc, argv);
1683                 return 0;
1684         }
1685
1686         ZERO_STRUCT(info1);
1687
1688         info1.lgrpi1_name = argv[0];
1689         if (c->opt_comment && strlen(c->opt_comment) > 0) {
1690                 info1.lgrpi1_comment = c->opt_comment;
1691         }
1692
1693         status = NetLocalGroupAdd(c->opt_host, 1, (uint8_t *)&info1, &parm_error);
1694
1695         if (status != 0) {
1696                 d_fprintf(stderr,
1697                         _("Failed to add alias '%s' with error: %s.\n"),
1698                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
1699                                                             status));
1700                 return -1;
1701         } else {
1702                 d_printf(_("Added alias '%s'.\n"), argv[0]);
1703         }
1704
1705         return 0;
1706 }
1707
1708 static int rpc_group_add(struct net_context *c, int argc, const char **argv)
1709 {
1710         if (c->opt_localgroup)
1711                 return rpc_alias_add_internals(c, argc, argv);
1712
1713         return rpc_group_add_internals(c, argc, argv);
1714 }
1715
1716 static NTSTATUS get_sid_from_name(struct cli_state *cli,
1717                                 TALLOC_CTX *mem_ctx,
1718                                 const char *name,
1719                                 DOM_SID *sid,
1720                                 enum lsa_SidType *type)
1721 {
1722         DOM_SID *sids = NULL;
1723         enum lsa_SidType *types = NULL;
1724         struct rpc_pipe_client *pipe_hnd = NULL;
1725         struct policy_handle lsa_pol;
1726         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1727
1728         result = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
1729                                           &pipe_hnd);
1730         if (!NT_STATUS_IS_OK(result)) {
1731                 goto done;
1732         }
1733
1734         result = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, false,
1735                                      SEC_FLAG_MAXIMUM_ALLOWED, &lsa_pol);
1736
1737         if (!NT_STATUS_IS_OK(result)) {
1738                 goto done;
1739         }
1740
1741         result = rpccli_lsa_lookup_names(pipe_hnd, mem_ctx, &lsa_pol, 1,
1742                                       &name, NULL, 1, &sids, &types);
1743
1744         if (NT_STATUS_IS_OK(result)) {
1745                 sid_copy(sid, &sids[0]);
1746                 *type = types[0];
1747         }
1748
1749         rpccli_lsa_Close(pipe_hnd, mem_ctx, &lsa_pol);
1750
1751  done:
1752         if (pipe_hnd) {
1753                 TALLOC_FREE(pipe_hnd);
1754         }
1755
1756         if (!NT_STATUS_IS_OK(result) && (StrnCaseCmp(name, "S-", 2) == 0)) {
1757
1758                 /* Try as S-1-5-whatever */
1759
1760                 DOM_SID tmp_sid;
1761
1762                 if (string_to_sid(&tmp_sid, name)) {
1763                         sid_copy(sid, &tmp_sid);
1764                         *type = SID_NAME_UNKNOWN;
1765                         result = NT_STATUS_OK;
1766                 }
1767         }
1768
1769         return result;
1770 }
1771
1772 static NTSTATUS rpc_add_groupmem(struct rpc_pipe_client *pipe_hnd,
1773                                 TALLOC_CTX *mem_ctx,
1774                                 const DOM_SID *group_sid,
1775                                 const char *member)
1776 {
1777         struct policy_handle connect_pol, domain_pol;
1778         NTSTATUS result;
1779         uint32 group_rid;
1780         struct policy_handle group_pol;
1781
1782         struct samr_Ids rids, rid_types;
1783         struct lsa_String lsa_acct_name;
1784
1785         DOM_SID sid;
1786
1787         sid_copy(&sid, group_sid);
1788
1789         if (!sid_split_rid(&sid, &group_rid)) {
1790                 return NT_STATUS_UNSUCCESSFUL;
1791         }
1792
1793         /* Get sam policy handle */
1794         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
1795                                       pipe_hnd->desthost,
1796                                       MAXIMUM_ALLOWED_ACCESS,
1797                                       &connect_pol);
1798         if (!NT_STATUS_IS_OK(result)) {
1799                 return result;
1800         }
1801
1802         /* Get domain policy handle */
1803         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
1804                                         &connect_pol,
1805                                         MAXIMUM_ALLOWED_ACCESS,
1806                                         &sid,
1807                                         &domain_pol);
1808         if (!NT_STATUS_IS_OK(result)) {
1809                 return result;
1810         }
1811
1812         init_lsa_String(&lsa_acct_name, member);
1813
1814         result = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
1815                                          &domain_pol,
1816                                          1,
1817                                          &lsa_acct_name,
1818                                          &rids,
1819                                          &rid_types);
1820
1821         if (!NT_STATUS_IS_OK(result)) {
1822                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
1823                           member);
1824                 goto done;
1825         }
1826
1827         result = rpccli_samr_OpenGroup(pipe_hnd, mem_ctx,
1828                                        &domain_pol,
1829                                        MAXIMUM_ALLOWED_ACCESS,
1830                                        group_rid,
1831                                        &group_pol);
1832
1833         if (!NT_STATUS_IS_OK(result)) {
1834                 goto done;
1835         }
1836
1837         result = rpccli_samr_AddGroupMember(pipe_hnd, mem_ctx,
1838                                             &group_pol,
1839                                             rids.ids[0],
1840                                             0x0005); /* unknown flags */
1841
1842  done:
1843         rpccli_samr_Close(pipe_hnd, mem_ctx, &connect_pol);
1844         return result;
1845 }
1846
1847 static NTSTATUS rpc_add_aliasmem(struct rpc_pipe_client *pipe_hnd,
1848                                 TALLOC_CTX *mem_ctx,
1849                                 const DOM_SID *alias_sid,
1850                                 const char *member)
1851 {
1852         struct policy_handle connect_pol, domain_pol;
1853         NTSTATUS result;
1854         uint32 alias_rid;
1855         struct policy_handle alias_pol;
1856
1857         DOM_SID member_sid;
1858         enum lsa_SidType member_type;
1859
1860         DOM_SID sid;
1861
1862         sid_copy(&sid, alias_sid);
1863
1864         if (!sid_split_rid(&sid, &alias_rid)) {
1865                 return NT_STATUS_UNSUCCESSFUL;
1866         }
1867
1868         result = get_sid_from_name(rpc_pipe_np_smb_conn(pipe_hnd), mem_ctx,
1869                                    member, &member_sid, &member_type);
1870
1871         if (!NT_STATUS_IS_OK(result)) {
1872                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
1873                           member);
1874                 return result;
1875         }
1876
1877         /* Get sam policy handle */
1878         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
1879                                       pipe_hnd->desthost,
1880                                       MAXIMUM_ALLOWED_ACCESS,
1881                                       &connect_pol);
1882         if (!NT_STATUS_IS_OK(result)) {
1883                 goto done;
1884         }
1885
1886         /* Get domain policy handle */
1887         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
1888                                         &connect_pol,
1889                                         MAXIMUM_ALLOWED_ACCESS,
1890                                         &sid,
1891                                         &domain_pol);
1892         if (!NT_STATUS_IS_OK(result)) {
1893                 goto done;
1894         }
1895
1896         result = rpccli_samr_OpenAlias(pipe_hnd, mem_ctx,
1897                                        &domain_pol,
1898                                        MAXIMUM_ALLOWED_ACCESS,
1899                                        alias_rid,
1900                                        &alias_pol);
1901
1902         if (!NT_STATUS_IS_OK(result)) {
1903                 return result;
1904         }
1905
1906         result = rpccli_samr_AddAliasMember(pipe_hnd, mem_ctx,
1907                                             &alias_pol,
1908                                             &member_sid);
1909
1910         if (!NT_STATUS_IS_OK(result)) {
1911                 return result;
1912         }
1913
1914  done:
1915         rpccli_samr_Close(pipe_hnd, mem_ctx, &connect_pol);
1916         return result;
1917 }
1918
1919 static NTSTATUS rpc_group_addmem_internals(struct net_context *c,
1920                                         const DOM_SID *domain_sid,
1921                                         const char *domain_name,
1922                                         struct cli_state *cli,
1923                                         struct rpc_pipe_client *pipe_hnd,
1924                                         TALLOC_CTX *mem_ctx,
1925                                         int argc,
1926                                         const char **argv)
1927 {
1928         DOM_SID group_sid;
1929         enum lsa_SidType group_type;
1930
1931         if (argc != 2 || c->display_usage) {
1932                 d_printf("%s\n%s",
1933                          _("Usage:"),
1934                          _("net rpc group addmem <group> <member>\n"
1935                            "  Add a member to a group\n"
1936                            "    group\tGroup to add member to\n"
1937                            "    member\tMember to add to group\n"));
1938                 return NT_STATUS_UNSUCCESSFUL;
1939         }
1940
1941         if (!NT_STATUS_IS_OK(get_sid_from_name(cli, mem_ctx, argv[0],
1942                                                &group_sid, &group_type))) {
1943                 d_fprintf(stderr, _("Could not lookup group name %s\n"),
1944                           argv[0]);
1945                 return NT_STATUS_UNSUCCESSFUL;
1946         }
1947
1948         if (group_type == SID_NAME_DOM_GRP) {
1949                 NTSTATUS result = rpc_add_groupmem(pipe_hnd, mem_ctx,
1950                                                    &group_sid, argv[1]);
1951
1952                 if (!NT_STATUS_IS_OK(result)) {
1953                         d_fprintf(stderr, _("Could not add %s to %s: %s\n"),
1954                                  argv[1], argv[0], nt_errstr(result));
1955                 }
1956                 return result;
1957         }
1958
1959         if (group_type == SID_NAME_ALIAS) {
1960                 NTSTATUS result = rpc_add_aliasmem(pipe_hnd, mem_ctx,
1961                                                    &group_sid, argv[1]);
1962
1963                 if (!NT_STATUS_IS_OK(result)) {
1964                         d_fprintf(stderr, _("Could not add %s to %s: %s\n"),
1965                                  argv[1], argv[0], nt_errstr(result));
1966                 }
1967                 return result;
1968         }
1969
1970         d_fprintf(stderr, _("Can only add members to global or local groups "
1971                  "which %s is not\n"), argv[0]);
1972
1973         return NT_STATUS_UNSUCCESSFUL;
1974 }
1975
1976 static int rpc_group_addmem(struct net_context *c, int argc, const char **argv)
1977 {
1978         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
1979                                rpc_group_addmem_internals,
1980                                argc, argv);
1981 }
1982
1983 static NTSTATUS rpc_del_groupmem(struct net_context *c,
1984                                 struct rpc_pipe_client *pipe_hnd,
1985                                 TALLOC_CTX *mem_ctx,
1986                                 const DOM_SID *group_sid,
1987                                 const char *member)
1988 {
1989         struct policy_handle connect_pol, domain_pol;
1990         NTSTATUS result;
1991         uint32 group_rid;
1992         struct policy_handle group_pol;
1993
1994         struct samr_Ids rids, rid_types;
1995         struct lsa_String lsa_acct_name;
1996
1997         DOM_SID sid;
1998
1999         sid_copy(&sid, group_sid);
2000
2001         if (!sid_split_rid(&sid, &group_rid))
2002                 return NT_STATUS_UNSUCCESSFUL;
2003
2004         /* Get sam policy handle */
2005         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
2006                                       pipe_hnd->desthost,
2007                                       MAXIMUM_ALLOWED_ACCESS,
2008                                       &connect_pol);
2009         if (!NT_STATUS_IS_OK(result))
2010                 return result;
2011
2012         /* Get domain policy handle */
2013         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
2014                                         &connect_pol,
2015                                         MAXIMUM_ALLOWED_ACCESS,
2016                                         &sid,
2017                                         &domain_pol);
2018         if (!NT_STATUS_IS_OK(result))
2019                 return result;
2020
2021         init_lsa_String(&lsa_acct_name, member);
2022
2023         result = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
2024                                          &domain_pol,
2025                                          1,
2026                                          &lsa_acct_name,
2027                                          &rids,
2028                                          &rid_types);
2029         if (!NT_STATUS_IS_OK(result)) {
2030                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2031                           member);
2032                 goto done;
2033         }
2034
2035         result = rpccli_samr_OpenGroup(pipe_hnd, mem_ctx,
2036                                        &domain_pol,
2037                                        MAXIMUM_ALLOWED_ACCESS,
2038                                        group_rid,
2039                                        &group_pol);
2040
2041         if (!NT_STATUS_IS_OK(result))
2042                 goto done;
2043
2044         result = rpccli_samr_DeleteGroupMember(pipe_hnd, mem_ctx,
2045                                                &group_pol,
2046                                                rids.ids[0]);
2047
2048  done:
2049         rpccli_samr_Close(pipe_hnd, mem_ctx, &connect_pol);
2050         return result;
2051 }
2052
2053 static NTSTATUS rpc_del_aliasmem(struct rpc_pipe_client *pipe_hnd,
2054                                 TALLOC_CTX *mem_ctx,
2055                                 const DOM_SID *alias_sid,
2056                                 const char *member)
2057 {
2058         struct policy_handle connect_pol, domain_pol;
2059         NTSTATUS result;
2060         uint32 alias_rid;
2061         struct policy_handle alias_pol;
2062
2063         DOM_SID member_sid;
2064         enum lsa_SidType member_type;
2065
2066         DOM_SID sid;
2067
2068         sid_copy(&sid, alias_sid);
2069
2070         if (!sid_split_rid(&sid, &alias_rid))
2071                 return NT_STATUS_UNSUCCESSFUL;
2072
2073         result = get_sid_from_name(rpc_pipe_np_smb_conn(pipe_hnd), mem_ctx,
2074                                    member, &member_sid, &member_type);
2075
2076         if (!NT_STATUS_IS_OK(result)) {
2077                 d_fprintf(stderr, _("Could not lookup up group member %s\n"),
2078                           member);
2079                 return result;
2080         }
2081
2082         /* Get sam policy handle */
2083         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
2084                                       pipe_hnd->desthost,
2085                                       MAXIMUM_ALLOWED_ACCESS,
2086                                       &connect_pol);
2087         if (!NT_STATUS_IS_OK(result)) {
2088                 goto done;
2089         }
2090
2091         /* Get domain policy handle */
2092         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
2093                                         &connect_pol,
2094                                         MAXIMUM_ALLOWED_ACCESS,
2095                                         &sid,
2096                                         &domain_pol);
2097         if (!NT_STATUS_IS_OK(result)) {
2098                 goto done;
2099         }
2100
2101         result = rpccli_samr_OpenAlias(pipe_hnd, mem_ctx,
2102                                        &domain_pol,
2103                                        MAXIMUM_ALLOWED_ACCESS,
2104                                        alias_rid,
2105                                        &alias_pol);
2106
2107         if (!NT_STATUS_IS_OK(result))
2108                 return result;
2109
2110         result = rpccli_samr_DeleteAliasMember(pipe_hnd, mem_ctx,
2111                                                &alias_pol,
2112                                                &member_sid);
2113
2114         if (!NT_STATUS_IS_OK(result))
2115                 return result;
2116
2117  done:
2118         rpccli_samr_Close(pipe_hnd, mem_ctx, &connect_pol);
2119         return result;
2120 }
2121
2122 static NTSTATUS rpc_group_delmem_internals(struct net_context *c,
2123                                         const DOM_SID *domain_sid,
2124                                         const char *domain_name,
2125                                         struct cli_state *cli,
2126                                         struct rpc_pipe_client *pipe_hnd,
2127                                         TALLOC_CTX *mem_ctx,
2128                                         int argc,
2129                                         const char **argv)
2130 {
2131         DOM_SID group_sid;
2132         enum lsa_SidType group_type;
2133
2134         if (argc != 2 || c->display_usage) {
2135                 d_printf("%s\n%s",
2136                          _("Usage:"),
2137                          _("net rpc group delmem <group> <member>\n"
2138                            "  Delete a member from a group\n"
2139                            "    group\tGroup to delete member from\n"
2140                            "    member\tMember to delete from group\n"));
2141                 return NT_STATUS_UNSUCCESSFUL;
2142         }
2143
2144         if (!NT_STATUS_IS_OK(get_sid_from_name(cli, mem_ctx, argv[0],
2145                                                &group_sid, &group_type))) {
2146                 d_fprintf(stderr, _("Could not lookup group name %s\n"),
2147                           argv[0]);
2148                 return NT_STATUS_UNSUCCESSFUL;
2149         }
2150
2151         if (group_type == SID_NAME_DOM_GRP) {
2152                 NTSTATUS result = rpc_del_groupmem(c, pipe_hnd, mem_ctx,
2153                                                    &group_sid, argv[1]);
2154
2155                 if (!NT_STATUS_IS_OK(result)) {
2156                         d_fprintf(stderr, _("Could not del %s from %s: %s\n"),
2157                                  argv[1], argv[0], nt_errstr(result));
2158                 }
2159                 return result;
2160         }
2161
2162         if (group_type == SID_NAME_ALIAS) {
2163                 NTSTATUS result = rpc_del_aliasmem(pipe_hnd, mem_ctx,
2164                                                    &group_sid, argv[1]);
2165
2166                 if (!NT_STATUS_IS_OK(result)) {
2167                         d_fprintf(stderr, _("Could not del %s from %s: %s\n"),
2168                                  argv[1], argv[0], nt_errstr(result));
2169                 }
2170                 return result;
2171         }
2172
2173         d_fprintf(stderr, _("Can only delete members from global or local "
2174                  "groups which %s is not\n"), argv[0]);
2175
2176         return NT_STATUS_UNSUCCESSFUL;
2177 }
2178
2179 static int rpc_group_delmem(struct net_context *c, int argc, const char **argv)
2180 {
2181         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
2182                                rpc_group_delmem_internals,
2183                                argc, argv);
2184 }
2185
2186 /**
2187  * List groups on a remote RPC server.
2188  *
2189  * All parameters are provided by the run_rpc_command function, except for
2190  * argc, argv which are passes through.
2191  *
2192  * @param domain_sid The domain sid acquired from the remote server.
2193  * @param cli A cli_state connected to the server.
2194  * @param mem_ctx Talloc context, destroyed on completion of the function.
2195  * @param argc  Standard main() style argc.
2196  * @param argv  Standard main() style argv. Initial components are already
2197  *              stripped.
2198  *
2199  * @return Normal NTSTATUS return.
2200  **/
2201
2202 static NTSTATUS rpc_group_list_internals(struct net_context *c,
2203                                         const DOM_SID *domain_sid,
2204                                         const char *domain_name,
2205                                         struct cli_state *cli,
2206                                         struct rpc_pipe_client *pipe_hnd,
2207                                         TALLOC_CTX *mem_ctx,
2208                                         int argc,
2209                                         const char **argv)
2210 {
2211         struct policy_handle connect_pol, domain_pol;
2212         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2213         uint32 start_idx=0, max_entries=250, num_entries, i, loop_count = 0;
2214         struct samr_SamArray *groups = NULL;
2215         bool global = false;
2216         bool local = false;
2217         bool builtin = false;
2218
2219         if (c->display_usage) {
2220                 d_printf("%s\n%s",
2221                          _("Usage:"),
2222                          _("net rpc group list [global] [local] [builtin]\n"
2223                            "  List groups on RPC server\n"
2224                            "    global\tList global groups\n"
2225                            "    local\tList local groups\n"
2226                            "    builtin\tList builtin groups\n"
2227                            "    If none of global, local or builtin is "
2228                            "specified, all three options are considered "
2229                            "set\n"));
2230                 return NT_STATUS_OK;
2231         }
2232
2233         if (argc == 0) {
2234                 global = true;
2235                 local = true;
2236                 builtin = true;
2237         }
2238
2239         for (i=0; i<argc; i++) {
2240                 if (strequal(argv[i], "global"))
2241                         global = true;
2242
2243                 if (strequal(argv[i], "local"))
2244                         local = true;
2245
2246                 if (strequal(argv[i], "builtin"))
2247                         builtin = true;
2248         }
2249
2250         /* Get sam policy handle */
2251
2252         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
2253                                       pipe_hnd->desthost,
2254                                       MAXIMUM_ALLOWED_ACCESS,
2255                                       &connect_pol);
2256         if (!NT_STATUS_IS_OK(result)) {
2257                 goto done;
2258         }
2259
2260         /* Get domain policy handle */
2261
2262         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
2263                                         &connect_pol,
2264                                         MAXIMUM_ALLOWED_ACCESS,
2265                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
2266                                         &domain_pol);
2267         if (!NT_STATUS_IS_OK(result)) {
2268                 goto done;
2269         }
2270
2271         /* Query domain groups */
2272         if (c->opt_long_list_entries)
2273                 d_printf(_("\nGroup name            Comment"
2274                            "\n-----------------------------\n"));
2275         do {
2276                 uint32_t max_size, total_size, returned_size;
2277                 union samr_DispInfo info;
2278
2279                 if (!global) break;
2280
2281                 get_query_dispinfo_params(
2282                         loop_count, &max_entries, &max_size);
2283
2284                 result = rpccli_samr_QueryDisplayInfo(pipe_hnd, mem_ctx,
2285                                                       &domain_pol,
2286                                                       3,
2287                                                       start_idx,
2288                                                       max_entries,
2289                                                       max_size,
2290                                                       &total_size,
2291                                                       &returned_size,
2292                                                       &info);
2293                 num_entries = info.info3.count;
2294                 start_idx += info.info3.count;
2295
2296                 if (!NT_STATUS_IS_OK(result) &&
2297                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
2298                         break;
2299
2300                 for (i = 0; i < num_entries; i++) {
2301
2302                         const char *group = NULL;
2303                         const char *desc = NULL;
2304
2305                         group = info.info3.entries[i].account_name.string;
2306                         desc = info.info3.entries[i].description.string;
2307
2308                         if (c->opt_long_list_entries)
2309                                 printf("%-21.21s %-50.50s\n",
2310                                        group, desc);
2311                         else
2312                                 printf("%s\n", group);
2313                 }
2314         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2315         /* query domain aliases */
2316         start_idx = 0;
2317         do {
2318                 if (!local) break;
2319
2320                 result = rpccli_samr_EnumDomainAliases(pipe_hnd, mem_ctx,
2321                                                        &domain_pol,
2322                                                        &start_idx,
2323                                                        &groups,
2324                                                        0xffff,
2325                                                        &num_entries);
2326                 if (!NT_STATUS_IS_OK(result) &&
2327                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
2328                         break;
2329
2330                 for (i = 0; i < num_entries; i++) {
2331
2332                         const char *description = NULL;
2333
2334                         if (c->opt_long_list_entries) {
2335
2336                                 struct policy_handle alias_pol;
2337                                 union samr_AliasInfo *info = NULL;
2338
2339                                 if ((NT_STATUS_IS_OK(rpccli_samr_OpenAlias(pipe_hnd, mem_ctx,
2340                                                                            &domain_pol,
2341                                                                            0x8,
2342                                                                            groups->entries[i].idx,
2343                                                                            &alias_pol))) &&
2344                                     (NT_STATUS_IS_OK(rpccli_samr_QueryAliasInfo(pipe_hnd, mem_ctx,
2345                                                                                 &alias_pol,
2346                                                                                 3,
2347                                                                                 &info))) &&
2348                                     (NT_STATUS_IS_OK(rpccli_samr_Close(pipe_hnd, mem_ctx,
2349                                                                     &alias_pol)))) {
2350                                         description = info->description.string;
2351                                 }
2352                         }
2353
2354                         if (description != NULL) {
2355                                 printf("%-21.21s %-50.50s\n",
2356                                        groups->entries[i].name.string,
2357                                        description);
2358                         } else {
2359                                 printf("%s\n", groups->entries[i].name.string);
2360                         }
2361                 }
2362         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2363         rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_pol);
2364         /* Get builtin policy handle */
2365
2366         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
2367                                         &connect_pol,
2368                                         MAXIMUM_ALLOWED_ACCESS,
2369                                         CONST_DISCARD(struct dom_sid2 *, &global_sid_Builtin),
2370                                         &domain_pol);
2371         if (!NT_STATUS_IS_OK(result)) {
2372                 goto done;
2373         }
2374         /* query builtin aliases */
2375         start_idx = 0;
2376         do {
2377                 if (!builtin) break;
2378
2379                 result = rpccli_samr_EnumDomainAliases(pipe_hnd, mem_ctx,
2380                                                        &domain_pol,
2381                                                        &start_idx,
2382                                                        &groups,
2383                                                        max_entries,
2384                                                        &num_entries);
2385                 if (!NT_STATUS_IS_OK(result) &&
2386                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
2387                         break;
2388
2389                 for (i = 0; i < num_entries; i++) {
2390
2391                         const char *description = NULL;
2392
2393                         if (c->opt_long_list_entries) {
2394
2395                                 struct policy_handle alias_pol;
2396                                 union samr_AliasInfo *info = NULL;
2397
2398                                 if ((NT_STATUS_IS_OK(rpccli_samr_OpenAlias(pipe_hnd, mem_ctx,
2399                                                                            &domain_pol,
2400                                                                            0x8,
2401                                                                            groups->entries[i].idx,
2402                                                                            &alias_pol))) &&
2403                                     (NT_STATUS_IS_OK(rpccli_samr_QueryAliasInfo(pipe_hnd, mem_ctx,
2404                                                                                 &alias_pol,
2405                                                                                 3,
2406                                                                                 &info))) &&
2407                                     (NT_STATUS_IS_OK(rpccli_samr_Close(pipe_hnd, mem_ctx,
2408                                                                     &alias_pol)))) {
2409                                         description = info->description.string;
2410                                 }
2411                         }
2412
2413                         if (description != NULL) {
2414                                 printf("%-21.21s %-50.50s\n",
2415                                        groups->entries[i].name.string,
2416                                        description);
2417                         } else {
2418                                 printf("%s\n", groups->entries[i].name.string);
2419                         }
2420                 }
2421         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
2422
2423  done:
2424         return result;
2425 }
2426
2427 static int rpc_group_list(struct net_context *c, int argc, const char **argv)
2428 {
2429         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
2430                                rpc_group_list_internals,
2431                                argc, argv);
2432 }
2433
2434 static NTSTATUS rpc_list_group_members(struct net_context *c,
2435                                         struct rpc_pipe_client *pipe_hnd,
2436                                         TALLOC_CTX *mem_ctx,
2437                                         const char *domain_name,
2438                                         const DOM_SID *domain_sid,
2439                                         struct policy_handle *domain_pol,
2440                                         uint32 rid)
2441 {
2442         NTSTATUS result;
2443         struct policy_handle group_pol;
2444         uint32 num_members, *group_rids;
2445         int i;
2446         struct samr_RidTypeArray *rids = NULL;
2447         struct lsa_Strings names;
2448         struct samr_Ids types;
2449
2450         fstring sid_str;
2451         sid_to_fstring(sid_str, domain_sid);
2452
2453         result = rpccli_samr_OpenGroup(pipe_hnd, mem_ctx,
2454                                        domain_pol,
2455                                        MAXIMUM_ALLOWED_ACCESS,
2456                                        rid,
2457                                        &group_pol);
2458
2459         if (!NT_STATUS_IS_OK(result))
2460                 return result;
2461
2462         result = rpccli_samr_QueryGroupMember(pipe_hnd, mem_ctx,
2463                                               &group_pol,
2464                                               &rids);
2465
2466         if (!NT_STATUS_IS_OK(result))
2467                 return result;
2468
2469         num_members = rids->count;
2470         group_rids = rids->rids;
2471
2472         while (num_members > 0) {
2473                 int this_time = 512;
2474
2475                 if (num_members < this_time)
2476                         this_time = num_members;
2477
2478                 result = rpccli_samr_LookupRids(pipe_hnd, mem_ctx,
2479                                                 domain_pol,
2480                                                 this_time,
2481                                                 group_rids,
2482                                                 &names,
2483                                                 &types);
2484
2485                 if (!NT_STATUS_IS_OK(result))
2486                         return result;
2487
2488                 /* We only have users as members, but make the output
2489                    the same as the output of alias members */
2490
2491                 for (i = 0; i < this_time; i++) {
2492
2493                         if (c->opt_long_list_entries) {
2494                                 printf("%s-%d %s\\%s %d\n", sid_str,
2495                                        group_rids[i], domain_name,
2496                                        names.names[i].string,
2497                                        SID_NAME_USER);
2498                         } else {
2499                                 printf("%s\\%s\n", domain_name,
2500                                         names.names[i].string);
2501                         }
2502                 }
2503
2504                 num_members -= this_time;
2505                 group_rids += 512;
2506         }
2507
2508         return NT_STATUS_OK;
2509 }
2510
2511 static NTSTATUS rpc_list_alias_members(struct net_context *c,
2512                                         struct rpc_pipe_client *pipe_hnd,
2513                                         TALLOC_CTX *mem_ctx,
2514                                         struct policy_handle *domain_pol,
2515                                         uint32 rid)
2516 {
2517         NTSTATUS result;
2518         struct rpc_pipe_client *lsa_pipe;
2519         struct policy_handle alias_pol, lsa_pol;
2520         uint32 num_members;
2521         DOM_SID *alias_sids;
2522         char **domains;
2523         char **names;
2524         enum lsa_SidType *types;
2525         int i;
2526         struct lsa_SidArray sid_array;
2527
2528         result = rpccli_samr_OpenAlias(pipe_hnd, mem_ctx,
2529                                        domain_pol,
2530                                        MAXIMUM_ALLOWED_ACCESS,
2531                                        rid,
2532                                        &alias_pol);
2533
2534         if (!NT_STATUS_IS_OK(result))
2535                 return result;
2536
2537         result = rpccli_samr_GetMembersInAlias(pipe_hnd, mem_ctx,
2538                                                &alias_pol,
2539                                                &sid_array);
2540
2541         if (!NT_STATUS_IS_OK(result)) {
2542                 d_fprintf(stderr, _("Couldn't list alias members\n"));
2543                 return result;
2544         }
2545
2546         num_members = sid_array.num_sids;
2547
2548         if (num_members == 0) {
2549                 return NT_STATUS_OK;
2550         }
2551
2552         result = cli_rpc_pipe_open_noauth(rpc_pipe_np_smb_conn(pipe_hnd),
2553                                           &ndr_table_lsarpc.syntax_id,
2554                                           &lsa_pipe);
2555         if (!NT_STATUS_IS_OK(result)) {
2556                 d_fprintf(stderr, _("Couldn't open LSA pipe. Error was %s\n"),
2557                         nt_errstr(result) );
2558                 return result;
2559         }
2560
2561         result = rpccli_lsa_open_policy(lsa_pipe, mem_ctx, true,
2562                                      SEC_FLAG_MAXIMUM_ALLOWED, &lsa_pol);
2563
2564         if (!NT_STATUS_IS_OK(result)) {
2565                 d_fprintf(stderr, _("Couldn't open LSA policy handle\n"));
2566                 TALLOC_FREE(lsa_pipe);
2567                 return result;
2568         }
2569
2570         alias_sids = TALLOC_ZERO_ARRAY(mem_ctx, DOM_SID, num_members);
2571         if (!alias_sids) {
2572                 d_fprintf(stderr, _("Out of memory\n"));
2573                 TALLOC_FREE(lsa_pipe);
2574                 return NT_STATUS_NO_MEMORY;
2575         }
2576
2577         for (i=0; i<num_members; i++) {
2578                 sid_copy(&alias_sids[i], sid_array.sids[i].sid);
2579         }
2580
2581         result = rpccli_lsa_lookup_sids(lsa_pipe, mem_ctx, &lsa_pol,
2582                                      num_members,  alias_sids,
2583                                      &domains, &names, &types);
2584
2585         if (!NT_STATUS_IS_OK(result) &&
2586             !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED)) {
2587                 d_fprintf(stderr, _("Couldn't lookup SIDs\n"));
2588                 TALLOC_FREE(lsa_pipe);
2589                 return result;
2590         }
2591
2592         for (i = 0; i < num_members; i++) {
2593                 fstring sid_str;
2594                 sid_to_fstring(sid_str, &alias_sids[i]);
2595
2596                 if (c->opt_long_list_entries) {
2597                         printf("%s %s\\%s %d\n", sid_str,
2598                                domains[i] ? domains[i] : _("*unknown*"),
2599                                names[i] ? names[i] : _("*unknown*"), types[i]);
2600                 } else {
2601                         if (domains[i])
2602                                 printf("%s\\%s\n", domains[i], names[i]);
2603                         else
2604                                 printf("%s\n", sid_str);
2605                 }
2606         }
2607
2608         TALLOC_FREE(lsa_pipe);
2609         return NT_STATUS_OK;
2610 }
2611
2612 static NTSTATUS rpc_group_members_internals(struct net_context *c,
2613                                         const DOM_SID *domain_sid,
2614                                         const char *domain_name,
2615                                         struct cli_state *cli,
2616                                         struct rpc_pipe_client *pipe_hnd,
2617                                         TALLOC_CTX *mem_ctx,
2618                                         int argc,
2619                                         const char **argv)
2620 {
2621         NTSTATUS result;
2622         struct policy_handle connect_pol, domain_pol;
2623         struct samr_Ids rids, rid_types;
2624         struct lsa_String lsa_acct_name;
2625
2626         /* Get sam policy handle */
2627
2628         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
2629                                       pipe_hnd->desthost,
2630                                       MAXIMUM_ALLOWED_ACCESS,
2631                                       &connect_pol);
2632
2633         if (!NT_STATUS_IS_OK(result))
2634                 return result;
2635
2636         /* Get domain policy handle */
2637
2638         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
2639                                         &connect_pol,
2640                                         MAXIMUM_ALLOWED_ACCESS,
2641                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
2642                                         &domain_pol);
2643
2644         if (!NT_STATUS_IS_OK(result))
2645                 return result;
2646
2647         init_lsa_String(&lsa_acct_name, argv[0]); /* sure? */
2648
2649         result = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
2650                                          &domain_pol,
2651                                          1,
2652                                          &lsa_acct_name,
2653                                          &rids,
2654                                          &rid_types);
2655
2656         if (!NT_STATUS_IS_OK(result)) {
2657
2658                 /* Ok, did not find it in the global sam, try with builtin */
2659
2660                 DOM_SID sid_Builtin;
2661
2662                 rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_pol);
2663
2664                 sid_copy(&sid_Builtin, &global_sid_Builtin);
2665
2666                 result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
2667                                                 &connect_pol,
2668                                                 MAXIMUM_ALLOWED_ACCESS,
2669                                                 &sid_Builtin,
2670                                                 &domain_pol);
2671
2672                 if (!NT_STATUS_IS_OK(result)) {
2673                         d_fprintf(stderr, _("Couldn't find group %s\n"),
2674                                   argv[0]);
2675                         return result;
2676                 }
2677
2678                 result = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
2679                                                  &domain_pol,
2680                                                  1,
2681                                                  &lsa_acct_name,
2682                                                  &rids,
2683                                                  &rid_types);
2684
2685                 if (!NT_STATUS_IS_OK(result)) {
2686                         d_fprintf(stderr, _("Couldn't find group %s\n"),
2687                                   argv[0]);
2688                         return result;
2689                 }
2690         }
2691
2692         if (rids.count != 1) {
2693                 d_fprintf(stderr, _("Couldn't find group %s\n"),
2694                           argv[0]);
2695                 return result;
2696         }
2697
2698         if (rid_types.ids[0] == SID_NAME_DOM_GRP) {
2699                 return rpc_list_group_members(c, pipe_hnd, mem_ctx, domain_name,
2700                                               domain_sid, &domain_pol,
2701                                               rids.ids[0]);
2702         }
2703
2704         if (rid_types.ids[0] == SID_NAME_ALIAS) {
2705                 return rpc_list_alias_members(c, pipe_hnd, mem_ctx, &domain_pol,
2706                                               rids.ids[0]);
2707         }
2708
2709         return NT_STATUS_NO_SUCH_GROUP;
2710 }
2711
2712 static int rpc_group_members(struct net_context *c, int argc, const char **argv)
2713 {
2714         if (argc != 1 || c->display_usage) {
2715                 return rpc_group_usage(c, argc, argv);
2716         }
2717
2718         return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
2719                                rpc_group_members_internals,
2720                                argc, argv);
2721 }
2722
2723 static int rpc_group_rename_internals(struct net_context *c, int argc, const char **argv)
2724 {
2725         NET_API_STATUS status;
2726         struct GROUP_INFO_0 g0;
2727         uint32_t parm_err;
2728
2729         if (argc != 2) {
2730                 d_printf(_("Usage:\n"));
2731                 d_printf("net rpc group rename group newname\n");
2732                 return -1;
2733         }
2734
2735         g0.grpi0_name = argv[1];
2736
2737         status = NetGroupSetInfo(c->opt_host,
2738                                  argv[0],
2739                                  0,
2740                                  (uint8_t *)&g0,
2741                                  &parm_err);
2742
2743         if (status != 0) {
2744                 d_fprintf(stderr, _("Renaming group %s failed with: %s\n"),
2745                         argv[0], libnetapi_get_error_string(c->netapi_ctx,
2746                         status));
2747                 return -1;
2748         }
2749
2750         return 0;
2751 }
2752
2753 static int rpc_group_rename(struct net_context *c, int argc, const char **argv)
2754 {
2755         if (argc != 2 || c->display_usage) {
2756                 return rpc_group_usage(c, argc, argv);
2757         }
2758
2759         return rpc_group_rename_internals(c, argc, argv);
2760 }
2761
2762 /**
2763  * 'net rpc group' entrypoint.
2764  * @param argc  Standard main() style argc.
2765  * @param argv  Standard main() style argv. Initial components are already
2766  *              stripped.
2767  **/
2768
2769 int net_rpc_group(struct net_context *c, int argc, const char **argv)
2770 {
2771         NET_API_STATUS status;
2772
2773         struct functable func[] = {
2774                 {
2775                         "add",
2776                         rpc_group_add,
2777                         NET_TRANSPORT_RPC,
2778                         N_("Create specified group"),
2779                         N_("net rpc group add\n"
2780                            "    Create specified group")
2781                 },
2782                 {
2783                         "delete",
2784                         rpc_group_delete,
2785                         NET_TRANSPORT_RPC,
2786                         N_("Delete specified group"),
2787                         N_("net rpc group delete\n"
2788                            "    Delete specified group")
2789                 },
2790                 {
2791                         "addmem",
2792                         rpc_group_addmem,
2793                         NET_TRANSPORT_RPC,
2794                         N_("Add member to group"),
2795                         N_("net rpc group addmem\n"
2796                            "    Add member to group")
2797                 },
2798                 {
2799                         "delmem",
2800                         rpc_group_delmem,
2801                         NET_TRANSPORT_RPC,
2802                         N_("Remove member from group"),
2803                         N_("net rpc group delmem\n"
2804                            "    Remove member from group")
2805                 },
2806                 {
2807                         "list",
2808                         rpc_group_list,
2809                         NET_TRANSPORT_RPC,
2810                         N_("List groups"),
2811                         N_("net rpc group list\n"
2812                            "    List groups")
2813                 },
2814                 {
2815                         "members",
2816                         rpc_group_members,
2817                         NET_TRANSPORT_RPC,
2818                         N_("List group members"),
2819                         N_("net rpc group members\n"
2820                            "    List group members")
2821                 },
2822                 {
2823                         "rename",
2824                         rpc_group_rename,
2825                         NET_TRANSPORT_RPC,
2826                         N_("Rename group"),
2827                         N_("net rpc group rename\n"
2828                            "    Rename group")
2829                 },
2830                 {NULL, NULL, 0, NULL, NULL}
2831         };
2832
2833         status = libnetapi_init(&c->netapi_ctx);
2834         if (status != 0) {
2835                 return -1;
2836         }
2837         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
2838         libnetapi_set_password(c->netapi_ctx, c->opt_password);
2839         if (c->opt_kerberos) {
2840                 libnetapi_set_use_kerberos(c->netapi_ctx);
2841         }
2842
2843         if (argc == 0) {
2844                 if (c->display_usage) {
2845                         d_printf(_("Usage:\n"));
2846                         d_printf(_("net rpc group\n"
2847                                    "    Alias for net rpc group list global "
2848                                    "local builtin\n"));
2849                         net_display_usage_from_functable(func);
2850                         return 0;
2851                 }
2852
2853                 return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
2854                                        rpc_group_list_internals,
2855                                        argc, argv);
2856         }
2857
2858         return net_run_function(c, argc, argv, "net rpc group", func);
2859 }
2860
2861 /****************************************************************************/
2862
2863 static int rpc_share_usage(struct net_context *c, int argc, const char **argv)
2864 {
2865         return net_share_usage(c, argc, argv);
2866 }
2867
2868 /**
2869  * Add a share on a remote RPC server.
2870  *
2871  * @param argc  Standard main() style argc.
2872  * @param argv  Standard main() style argv. Initial components are already
2873  *              stripped.
2874  *
2875  * @return A shell status integer (0 for success).
2876  **/
2877
2878 static int rpc_share_add(struct net_context *c, int argc, const char **argv)
2879 {
2880         NET_API_STATUS status;
2881         char *sharename;
2882         char *path;
2883         uint32 type = STYPE_DISKTREE; /* only allow disk shares to be added */
2884         uint32 num_users=0, perms=0;
2885         char *password=NULL; /* don't allow a share password */
2886         struct SHARE_INFO_2 i2;
2887         uint32_t parm_error = 0;
2888
2889         if ((argc < 1) || !strchr(argv[0], '=') || c->display_usage) {
2890                 return rpc_share_usage(c, argc, argv);
2891         }
2892
2893         if ((sharename = talloc_strdup(c, argv[0])) == NULL) {
2894                 return -1;
2895         }
2896
2897         path = strchr(sharename, '=');
2898         if (!path) {
2899                 return -1;
2900         }
2901
2902         *path++ = '\0';
2903
2904         i2.shi2_netname         = sharename;
2905         i2.shi2_type            = type;
2906         i2.shi2_remark          = c->opt_comment;
2907         i2.shi2_permissions     = perms;
2908         i2.shi2_max_uses        = c->opt_maxusers;
2909         i2.shi2_current_uses    = num_users;
2910         i2.shi2_path            = path;
2911         i2.shi2_passwd          = password;
2912
2913         status = NetShareAdd(c->opt_host,
2914                              2,
2915                              (uint8_t *)&i2,
2916                              &parm_error);
2917         if (status != 0) {
2918                 printf(_("NetShareAdd failed with: %s\n"),
2919                         libnetapi_get_error_string(c->netapi_ctx, status));
2920         }
2921
2922         return status;
2923 }
2924
2925 /**
2926  * Delete a share on a remote RPC server.
2927  *
2928  * @param domain_sid The domain sid acquired from the remote server.
2929  * @param argc  Standard main() style argc.
2930  * @param argv  Standard main() style argv. Initial components are already
2931  *              stripped.
2932  *
2933  * @return A shell status integer (0 for success).
2934  **/
2935 static int rpc_share_delete(struct net_context *c, int argc, const char **argv)
2936 {
2937         if (argc < 1 || c->display_usage) {
2938                 return rpc_share_usage(c, argc, argv);
2939         }
2940
2941         return NetShareDel(c->opt_host, argv[0], 0);
2942 }
2943
2944 /**
2945  * Formatted print of share info
2946  *
2947  * @param r  pointer to SHARE_INFO_1 to format
2948  **/
2949
2950 static void display_share_info_1(struct net_context *c,
2951                                  struct SHARE_INFO_1 *r)
2952 {
2953         if (c->opt_long_list_entries) {
2954                 d_printf("%-12s %-8.8s %-50s\n",
2955                          r->shi1_netname,
2956                          net_share_type_str(r->shi1_type & ~(STYPE_TEMPORARY|STYPE_HIDDEN)),
2957                          r->shi1_remark);
2958         } else {
2959                 d_printf("%s\n", r->shi1_netname);
2960         }
2961 }
2962
2963 static WERROR get_share_info(struct net_context *c,
2964                              struct rpc_pipe_client *pipe_hnd,
2965                              TALLOC_CTX *mem_ctx,
2966                              uint32 level,
2967                              int argc,
2968                              const char **argv,
2969                              struct srvsvc_NetShareInfoCtr *info_ctr)
2970 {
2971         WERROR result;
2972         NTSTATUS status;
2973         union srvsvc_NetShareInfo info;
2974
2975         /* no specific share requested, enumerate all */
2976         if (argc == 0) {
2977
2978                 uint32_t preferred_len = 0xffffffff;
2979                 uint32_t total_entries = 0;
2980                 uint32_t resume_handle = 0;
2981
2982                 info_ctr->level = level;
2983
2984                 status = rpccli_srvsvc_NetShareEnumAll(pipe_hnd, mem_ctx,
2985                                                        pipe_hnd->desthost,
2986                                                        info_ctr,
2987                                                        preferred_len,
2988                                                        &total_entries,
2989                                                        &resume_handle,
2990                                                        &result);
2991                 return result;
2992         }
2993
2994         /* request just one share */
2995         status = rpccli_srvsvc_NetShareGetInfo(pipe_hnd, mem_ctx,
2996                                                pipe_hnd->desthost,
2997                                                argv[0],
2998                                                level,
2999                                                &info,
3000                                                &result);
3001
3002         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(result)) {
3003                 goto done;
3004         }
3005
3006         /* construct ctr */
3007         ZERO_STRUCTP(info_ctr);
3008
3009         info_ctr->level = level;
3010
3011         switch (level) {
3012         case 1:
3013         {
3014                 struct srvsvc_NetShareCtr1 *ctr1;
3015
3016                 ctr1 = TALLOC_ZERO_P(mem_ctx, struct srvsvc_NetShareCtr1);
3017                 W_ERROR_HAVE_NO_MEMORY(ctr1);
3018
3019                 ctr1->count = 1;
3020                 ctr1->array = info.info1;
3021
3022                 info_ctr->ctr.ctr1 = ctr1;
3023         }
3024         case 2:
3025         {
3026                 struct srvsvc_NetShareCtr2 *ctr2;
3027
3028                 ctr2 = TALLOC_ZERO_P(mem_ctx, struct srvsvc_NetShareCtr2);
3029                 W_ERROR_HAVE_NO_MEMORY(ctr2);
3030
3031                 ctr2->count = 1;
3032                 ctr2->array = info.info2;
3033
3034                 info_ctr->ctr.ctr2 = ctr2;
3035         }
3036         case 502:
3037         {
3038                 struct srvsvc_NetShareCtr502 *ctr502;
3039
3040                 ctr502 = TALLOC_ZERO_P(mem_ctx, struct srvsvc_NetShareCtr502);
3041                 W_ERROR_HAVE_NO_MEMORY(ctr502);
3042
3043                 ctr502->count = 1;
3044                 ctr502->array = info.info502;
3045
3046                 info_ctr->ctr.ctr502 = ctr502;
3047         }
3048         } /* switch */
3049 done:
3050         return result;
3051 }
3052
3053 /***
3054  * 'net rpc share list' entrypoint.
3055  * @param argc  Standard main() style argc.
3056  * @param argv  Standard main() style argv. Initial components are already
3057  *              stripped.
3058  **/
3059 static int rpc_share_list(struct net_context *c, int argc, const char **argv)
3060 {
3061         NET_API_STATUS status;
3062         struct SHARE_INFO_1 *i1 = NULL;
3063         uint32_t entries_read = 0;
3064         uint32_t total_entries = 0;
3065         uint32_t resume_handle = 0;
3066         uint32_t i, level = 1;
3067
3068         if (c->display_usage) {
3069                 d_printf(  "%s\n"
3070                            "net rpc share list\n"
3071                            "    %s\n",
3072                          _("Usage:"),
3073                          _("List shares on remote server"));
3074                 return 0;
3075         }
3076
3077         status = NetShareEnum(c->opt_host,
3078                               level,
3079                               (uint8_t **)(void *)&i1,
3080                               (uint32_t)-1,
3081                               &entries_read,
3082                               &total_entries,
3083                               &resume_handle);
3084         if (status != 0) {
3085                 goto done;
3086         }
3087
3088         /* Display results */
3089
3090         if (c->opt_long_list_entries) {
3091                 d_printf(_(
3092         "\nEnumerating shared resources (exports) on remote server:\n\n"
3093         "\nShare name   Type     Description\n"
3094         "----------   ----     -----------\n"));
3095         }
3096         for (i = 0; i < entries_read; i++)
3097                 display_share_info_1(c, &i1[i]);
3098  done:
3099         return status;
3100 }
3101
3102 static bool check_share_availability(struct cli_state *cli, const char *netname)
3103 {
3104         NTSTATUS status;
3105
3106         status = cli_tcon_andx(cli, netname, "A:", "", 0);
3107         if (!NT_STATUS_IS_OK(status)) {
3108                 d_printf(_("skipping   [%s]: not a file share.\n"), netname);
3109                 return false;
3110         }
3111
3112         status = cli_tdis(cli);
3113         if (!NT_STATUS_IS_OK(status)) {
3114                 d_printf(_("cli_tdis returned %s\n"), nt_errstr(status));
3115                 return false;
3116         }
3117
3118         return true;
3119 }
3120
3121 static bool check_share_sanity(struct net_context *c, struct cli_state *cli,
3122                                const char *netname, uint32 type)
3123 {
3124         /* only support disk shares */
3125         if (! ( type == STYPE_DISKTREE || type == (STYPE_DISKTREE | STYPE_HIDDEN)) ) {
3126                 printf(_("share [%s] is not a diskshare (type: %x)\n"), netname,
3127                        type);
3128                 return false;
3129         }
3130
3131         /* skip builtin shares */
3132         /* FIXME: should print$ be added too ? */
3133         if (strequal(netname,"IPC$") || strequal(netname,"ADMIN$") ||
3134             strequal(netname,"global"))
3135                 return false;
3136
3137         if (c->opt_exclude && in_list(netname, c->opt_exclude, false)) {
3138                 printf(_("excluding  [%s]\n"), netname);
3139                 return false;
3140         }
3141
3142         return check_share_availability(cli, netname);
3143 }
3144
3145 /**
3146  * Migrate shares from a remote RPC server to the local RPC server.
3147  *
3148  * All parameters are provided by the run_rpc_command function, except for
3149  * argc, argv which are passed through.
3150  *
3151  * @param domain_sid The domain sid acquired from the remote server.
3152  * @param cli A cli_state connected to the server.
3153  * @param mem_ctx Talloc context, destroyed on completion of the function.
3154  * @param argc  Standard main() style argc.
3155  * @param argv  Standard main() style argv. Initial components are already
3156  *              stripped.
3157  *
3158  * @return Normal NTSTATUS return.
3159  **/
3160
3161 static NTSTATUS rpc_share_migrate_shares_internals(struct net_context *c,
3162                                                 const DOM_SID *domain_sid,
3163                                                 const char *domain_name,
3164                                                 struct cli_state *cli,
3165                                                 struct rpc_pipe_client *pipe_hnd,
3166                                                 TALLOC_CTX *mem_ctx,
3167                                                 int argc,
3168                                                 const char **argv)
3169 {
3170         WERROR result;
3171         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
3172         struct srvsvc_NetShareInfoCtr ctr_src;
3173         uint32 i;
3174         struct rpc_pipe_client *srvsvc_pipe = NULL;
3175         struct cli_state *cli_dst = NULL;
3176         uint32 level = 502; /* includes secdesc */
3177         uint32_t parm_error = 0;
3178
3179         result = get_share_info(c, pipe_hnd, mem_ctx, level, argc, argv,
3180                                 &ctr_src);
3181         if (!W_ERROR_IS_OK(result))
3182                 goto done;
3183
3184         /* connect destination PI_SRVSVC */
3185         nt_status = connect_dst_pipe(c, &cli_dst, &srvsvc_pipe,
3186                                      &ndr_table_srvsvc.syntax_id);
3187         if (!NT_STATUS_IS_OK(nt_status))
3188                 return nt_status;
3189
3190
3191         for (i = 0; i < ctr_src.ctr.ctr502->count; i++) {
3192
3193                 union srvsvc_NetShareInfo info;
3194                 struct srvsvc_NetShareInfo502 info502 =
3195                         ctr_src.ctr.ctr502->array[i];
3196
3197                 /* reset error-code */
3198                 nt_status = NT_STATUS_UNSUCCESSFUL;
3199
3200                 if (!check_share_sanity(c, cli, info502.name, info502.type))
3201                         continue;
3202
3203                 /* finally add the share on the dst server */
3204
3205                 printf(_("migrating: [%s], path: %s, comment: %s, without "
3206                          "share-ACLs\n"),
3207                         info502.name, info502.path, info502.comment);
3208
3209                 info.info502 = &info502;
3210
3211                 nt_status = rpccli_srvsvc_NetShareAdd(srvsvc_pipe, mem_ctx,
3212                                                       srvsvc_pipe->desthost,
3213                                                       502,
3214                                                       &info,
3215                                                       &parm_error,
3216                                                       &result);
3217
3218                 if (W_ERROR_V(result) == W_ERROR_V(WERR_FILE_EXISTS)) {
3219                         printf(_("           [%s] does already exist\n"),
3220                                 info502.name);
3221                         continue;
3222                 }
3223
3224                 if (!NT_STATUS_IS_OK(nt_status) || !W_ERROR_IS_OK(result)) {
3225                         printf(_("cannot add share: %s\n"), win_errstr(result));
3226                         goto done;
3227                 }
3228
3229         }
3230
3231         nt_status = NT_STATUS_OK;
3232
3233 done:
3234         if (cli_dst) {
3235                 cli_shutdown(cli_dst);
3236         }
3237
3238         return nt_status;
3239
3240 }
3241
3242 /**
3243  * Migrate shares from a RPC server to another.
3244  *
3245  * @param argc  Standard main() style argc.
3246  * @param argv  Standard main() style argv. Initial components are already
3247  *              stripped.
3248  *
3249  * @return A shell status integer (0 for success).
3250  **/
3251 static int rpc_share_migrate_shares(struct net_context *c, int argc,
3252                                     const char **argv)
3253 {
3254         if (c->display_usage) {
3255                 d_printf(  "%s\n"
3256                            "net rpc share migrate shares\n"
3257                            "    %s\n",
3258                          _("Usage:"),
3259                          _("Migrate shares to local server"));
3260                 return 0;
3261         }
3262
3263         if (!c->opt_host) {
3264                 printf(_("no server to migrate\n"));
3265                 return -1;
3266         }
3267
3268         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
3269                                rpc_share_migrate_shares_internals,
3270                                argc, argv);
3271 }
3272
3273 /**
3274  * Copy a file/dir
3275  *
3276  * @param f     file_info
3277  * @param mask  current search mask
3278  * @param state arg-pointer
3279  *
3280  **/
3281 static void copy_fn(const char *mnt, file_info *f,
3282                     const char *mask, void *state)
3283 {
3284         static NTSTATUS nt_status;
3285         static struct copy_clistate *local_state;
3286         static fstring filename, new_mask;
3287         fstring dir;
3288         char *old_dir;
3289         struct net_context *c;
3290
3291         local_state = (struct copy_clistate *)state;
3292         nt_status = NT_STATUS_UNSUCCESSFUL;
3293
3294         c = local_state->c;
3295
3296         if (strequal(f->name, ".") || strequal(f->name, ".."))
3297                 return;
3298
3299         DEBUG(3,("got mask: %s, name: %s\n", mask, f->name));
3300
3301         /* DIRECTORY */
3302         if (f->mode & aDIR) {
3303
3304                 DEBUG(3,("got dir: %s\n", f->name));
3305
3306                 fstrcpy(dir, local_state->cwd);
3307                 fstrcat(dir, "\\");
3308                 fstrcat(dir, f->name);
3309
3310                 switch (net_mode_share)
3311                 {
3312                 case NET_MODE_SHARE_MIGRATE:
3313                         /* create that directory */
3314                         nt_status = net_copy_file(c, local_state->mem_ctx,
3315                                                   local_state->cli_share_src,
3316                                                   local_state->cli_share_dst,
3317                                                   dir, dir,
3318                                                   c->opt_acls? true : false,
3319                                                   c->opt_attrs? true : false,
3320                                                   c->opt_timestamps? true:false,
3321                                                   false);
3322                         break;
3323                 default:
3324                         d_fprintf(stderr, _("Unsupported mode %d\n"), net_mode_share);
3325                         return;
3326                 }
3327
3328                 if (!NT_STATUS_IS_OK(nt_status))
3329                         printf(_("could not handle dir %s: %s\n"),
3330                                 dir, nt_errstr(nt_status));
3331
3332                 /* search below that directory */
3333                 fstrcpy(new_mask, dir);
3334                 fstrcat(new_mask, "\\*");
3335
3336                 old_dir = local_state->cwd;
3337                 local_state->cwd = dir;
3338                 if (!sync_files(local_state, new_mask))
3339                         printf(_("could not handle files\n"));
3340                 local_state->cwd = old_dir;
3341
3342                 return;
3343         }
3344
3345
3346         /* FILE */
3347         fstrcpy(filename, local_state->cwd);
3348         fstrcat(filename, "\\");
3349         fstrcat(filename, f->name);
3350
3351         DEBUG(3,("got file: %s\n", filename));
3352
3353         switch (net_mode_share)
3354         {
3355         case NET_MODE_SHARE_MIGRATE:
3356                 nt_status = net_copy_file(c, local_state->mem_ctx,
3357                                           local_state->cli_share_src,
3358                                           local_state->cli_share_dst,
3359                                           filename, filename,
3360                                           c->opt_acls? true : false,
3361                                           c->opt_attrs? true : false,
3362                                           c->opt_timestamps? true: false,
3363                                           true);
3364                 break;
3365         default:
3366                 d_fprintf(stderr, _("Unsupported file mode %d\n"),
3367                           net_mode_share);
3368                 return;
3369         }
3370
3371         if (!NT_STATUS_IS_OK(nt_status))
3372                 printf(_("could not handle file %s: %s\n"),
3373                         filename, nt_errstr(nt_status));
3374
3375 }
3376
3377 /**
3378  * sync files, can be called recursivly to list files
3379  * and then call copy_fn for each file
3380  *
3381  * @param cp_clistate   pointer to the copy_clistate we work with
3382  * @param mask          the current search mask
3383  *
3384  * @return              Boolean result
3385  **/
3386 static bool sync_files(struct copy_clistate *cp_clistate, const char *mask)
3387 {
3388         struct cli_state *targetcli;
3389         char *targetpath = NULL;
3390
3391         DEBUG(3,("calling cli_list with mask: %s\n", mask));
3392
3393         if ( !cli_resolve_path(talloc_tos(), "", NULL, cp_clistate->cli_share_src,
3394                                 mask, &targetcli, &targetpath ) ) {
3395                 d_fprintf(stderr, _("cli_resolve_path %s failed with error: "
3396                                     "%s\n"),
3397                         mask, cli_errstr(cp_clistate->cli_share_src));
3398                 return false;
3399         }
3400
3401         if (cli_list(targetcli, targetpath, cp_clistate->attribute, copy_fn, cp_clistate) == -1) {
3402                 d_fprintf(stderr, _("listing %s failed with error: %s\n"),
3403                         mask, cli_errstr(targetcli));
3404                 return false;
3405         }
3406
3407         return true;
3408 }
3409
3410
3411 /**
3412  * Set the top level directory permissions before we do any further copies.
3413  * Should set up ACL inheritance.
3414  **/
3415
3416 bool copy_top_level_perms(struct net_context *c,
3417                                 struct copy_clistate *cp_clistate,
3418                                 const char *sharename)
3419 {
3420         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
3421
3422         switch (net_mode_share) {
3423         case NET_MODE_SHARE_MIGRATE:
3424                 DEBUG(3,("calling net_copy_fileattr for '.' directory in share %s\n", sharename));
3425                 nt_status = net_copy_fileattr(c,
3426                                                 cp_clistate->mem_ctx,
3427                                                 cp_clistate->cli_share_src,
3428                                                 cp_clistate->cli_share_dst,
3429                                                 "\\", "\\",
3430                                                 c->opt_acls? true : false,
3431                                                 c->opt_attrs? true : false,
3432                                                 c->opt_timestamps? true: false,
3433                                                 false);
3434                 break;
3435         default:
3436                 d_fprintf(stderr, _("Unsupported mode %d\n"), net_mode_share);
3437                 break;
3438         }
3439
3440         if (!NT_STATUS_IS_OK(nt_status))  {
3441                 printf(_("Could handle directory attributes for top level "
3442                          "directory of share %s. Error %s\n"),
3443                         sharename, nt_errstr(nt_status));
3444                 return false;
3445         }
3446
3447         return true;
3448 }
3449
3450 /**
3451  * Sync all files inside a remote share to another share (over smb).
3452  *
3453  * All parameters are provided by the run_rpc_command function, except for
3454  * argc, argv which are passed through.
3455  *
3456  * @param domain_sid The domain sid acquired from the remote server.
3457  * @param cli A cli_state connected to the server.
3458  * @param mem_ctx Talloc context, destroyed on completion of the function.
3459  * @param argc  Standard main() style argc.
3460  * @param argv  Standard main() style argv. Initial components are already
3461  *              stripped.
3462  *
3463  * @return Normal NTSTATUS return.
3464  **/
3465
3466 static NTSTATUS rpc_share_migrate_files_internals(struct net_context *c,
3467                                                 const DOM_SID *domain_sid,
3468                                                 const char *domain_name,
3469                                                 struct cli_state *cli,
3470                                                 struct rpc_pipe_client *pipe_hnd,
3471                                                 TALLOC_CTX *mem_ctx,
3472                                                 int argc,
3473                                                 const char **argv)
3474 {
3475         WERROR result;
3476         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
3477         struct srvsvc_NetShareInfoCtr ctr_src;
3478         uint32 i;
3479         uint32 level = 502;
3480         struct copy_clistate cp_clistate;
3481         bool got_src_share = false;
3482         bool got_dst_share = false;
3483         const char *mask = "\\*";
3484         char *dst = NULL;
3485
3486         dst = SMB_STRDUP(c->opt_destination?c->opt_destination:"127.0.0.1");
3487         if (dst == NULL) {
3488                 nt_status = NT_STATUS_NO_MEMORY;
3489                 goto done;
3490         }
3491
3492         result = get_share_info(c, pipe_hnd, mem_ctx, level, argc, argv,
3493                                 &ctr_src);
3494
3495         if (!W_ERROR_IS_OK(result))
3496                 goto done;
3497
3498         for (i = 0; i < ctr_src.ctr.ctr502->count; i++) {
3499
3500                 struct srvsvc_NetShareInfo502 info502 =
3501                         ctr_src.ctr.ctr502->array[i];
3502
3503                 if (!check_share_sanity(c, cli, info502.name, info502.type))
3504                         continue;
3505
3506                 /* one might not want to mirror whole discs :) */
3507                 if (strequal(info502.name, "print$") || info502.name[1] == '$') {
3508                         d_printf(_("skipping   [%s]: builtin/hidden share\n"),
3509                                  info502.name);
3510                         continue;
3511                 }
3512
3513                 switch (net_mode_share)
3514                 {
3515                 case NET_MODE_SHARE_MIGRATE:
3516                         printf("syncing");
3517                         break;
3518                 default:
3519                         d_fprintf(stderr, _("Unsupported mode %d\n"),
3520                                   net_mode_share);
3521                         break;
3522                 }
3523                 printf(_("    [%s] files and directories %s ACLs, %s DOS "
3524                          "Attributes %s\n"),
3525                         info502.name,
3526                         c->opt_acls ? _("including") : _("without"),
3527                         c->opt_attrs ? _("including") : _("without"),
3528                         c->opt_timestamps ? _("(preserving timestamps)") : "");
3529
3530                 cp_clistate.mem_ctx = mem_ctx;
3531                 cp_clistate.cli_share_src = NULL;
3532                 cp_clistate.cli_share_dst = NULL;
3533                 cp_clistate.cwd = NULL;
3534                 cp_clistate.attribute = aSYSTEM | aHIDDEN | aDIR;
3535                 cp_clistate.c = c;
3536
3537                 /* open share source */
3538                 nt_status = connect_to_service(c, &cp_clistate.cli_share_src,
3539                                                &cli->dest_ss, cli->desthost,
3540                                                info502.name, "A:");
3541                 if (!NT_STATUS_IS_OK(nt_status))
3542                         goto done;
3543
3544                 got_src_share = true;
3545
3546                 if (net_mode_share == NET_MODE_SHARE_MIGRATE) {
3547                         /* open share destination */
3548                         nt_status = connect_to_service(c, &cp_clistate.cli_share_dst,
3549                                                        NULL, dst, info502.name, "A:");
3550                         if (!NT_STATUS_IS_OK(nt_status))
3551                                 goto done;
3552
3553                         got_dst_share = true;
3554                 }
3555
3556                 if (!copy_top_level_perms(c, &cp_clistate, info502.name)) {
3557                         d_fprintf(stderr, _("Could not handle the top level "
3558                                             "directory permissions for the "
3559                                             "share: %s\n"), info502.name);
3560                         nt_status = NT_STATUS_UNSUCCESSFUL;
3561                         goto done;
3562                 }
3563
3564                 if (!sync_files(&cp_clistate, mask)) {
3565                         d_fprintf(stderr, _("could not handle files for share: "
3566                                             "%s\n"), info502.name);
3567                         nt_status = NT_STATUS_UNSUCCESSFUL;
3568                         goto done;
3569                 }
3570         }
3571
3572         nt_status = NT_STATUS_OK;
3573
3574 done:
3575
3576         if (got_src_share)
3577                 cli_shutdown(cp_clistate.cli_share_src);
3578
3579         if (got_dst_share)
3580                 cli_shutdown(cp_clistate.cli_share_dst);
3581
3582         SAFE_FREE(dst);
3583         return nt_status;
3584
3585 }
3586
3587 static int rpc_share_migrate_files(struct net_context *c, int argc, const char **argv)
3588 {
3589         if (c->display_usage) {
3590                 d_printf(  "%s\n"
3591                            "net share migrate files\n"
3592                            "    %s\n",
3593                          _("Usage:"),
3594                          _("Migrate files to local server"));
3595                 return 0;
3596         }
3597
3598         if (!c->opt_host) {
3599                 d_printf(_("no server to migrate\n"));
3600                 return -1;
3601         }
3602
3603         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
3604                                rpc_share_migrate_files_internals,
3605                                argc, argv);
3606 }
3607
3608 /**
3609  * Migrate share-ACLs from a remote RPC server to the local RPC server.
3610  *
3611  * All parameters are provided by the run_rpc_command function, except for
3612  * argc, argv which are passed through.
3613  *
3614  * @param domain_sid The domain sid acquired from the remote server.
3615  * @param cli A cli_state connected to the server.
3616  * @param mem_ctx Talloc context, destroyed on completion of the function.
3617  * @param argc  Standard main() style argc.
3618  * @param argv  Standard main() style argv. Initial components are already
3619  *              stripped.
3620  *
3621  * @return Normal NTSTATUS return.
3622  **/
3623
3624 static NTSTATUS rpc_share_migrate_security_internals(struct net_context *c,
3625                                                 const DOM_SID *domain_sid,
3626                                                 const char *domain_name,
3627                                                 struct cli_state *cli,
3628                                                 struct rpc_pipe_client *pipe_hnd,
3629                                                 TALLOC_CTX *mem_ctx,
3630                                                 int argc,
3631                                                 const char **argv)
3632 {
3633         WERROR result;
3634         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
3635         struct srvsvc_NetShareInfoCtr ctr_src;
3636         union srvsvc_NetShareInfo info;
3637         uint32 i;
3638         struct rpc_pipe_client *srvsvc_pipe = NULL;
3639         struct cli_state *cli_dst = NULL;
3640         uint32 level = 502; /* includes secdesc */
3641         uint32_t parm_error = 0;
3642
3643         result = get_share_info(c, pipe_hnd, mem_ctx, level, argc, argv,
3644                                 &ctr_src);
3645
3646         if (!W_ERROR_IS_OK(result))
3647                 goto done;
3648
3649         /* connect destination PI_SRVSVC */
3650         nt_status = connect_dst_pipe(c, &cli_dst, &srvsvc_pipe,
3651                                      &ndr_table_srvsvc.syntax_id);
3652         if (!NT_STATUS_IS_OK(nt_status))
3653                 return nt_status;
3654
3655
3656         for (i = 0; i < ctr_src.ctr.ctr502->count; i++) {
3657
3658                 struct srvsvc_NetShareInfo502 info502 =
3659                         ctr_src.ctr.ctr502->array[i];
3660
3661                 /* reset error-code */
3662                 nt_status = NT_STATUS_UNSUCCESSFUL;
3663
3664                 if (!check_share_sanity(c, cli, info502.name, info502.type))
3665                         continue;
3666
3667                 printf(_("migrating: [%s], path: %s, comment: %s, including "
3668                          "share-ACLs\n"),
3669                         info502.name, info502.path, info502.comment);
3670
3671                 if (c->opt_verbose)
3672                         display_sec_desc(info502.sd_buf.sd);
3673
3674                 /* FIXME: shouldn't we be able to just set the security descriptor ? */
3675                 info.info502 = &info502;
3676
3677                 /* finally modify the share on the dst server */
3678                 nt_status = rpccli_srvsvc_NetShareSetInfo(srvsvc_pipe, mem_ctx,
3679                                                           srvsvc_pipe->desthost,
3680                                                           info502.name,
3681                                                           level,
3682                                                           &info,
3683                                                           &parm_error,
3684                                                           &result);
3685                 if (!NT_STATUS_IS_OK(nt_status) || !W_ERROR_IS_OK(result)) {
3686                         printf(_("cannot set share-acl: %s\n"),
3687                                win_errstr(result));
3688                         goto done;
3689                 }
3690
3691         }
3692
3693         nt_status = NT_STATUS_OK;
3694
3695 done:
3696         if (cli_dst) {
3697                 cli_shutdown(cli_dst);
3698         }
3699
3700         return nt_status;
3701
3702 }
3703
3704 /**
3705  * Migrate share-acls from a RPC server to another.
3706  *
3707  * @param argc  Standard main() style argc.
3708  * @param argv  Standard main() style argv. Initial components are already
3709  *              stripped.
3710  *
3711  * @return A shell status integer (0 for success).
3712  **/
3713 static int rpc_share_migrate_security(struct net_context *c, int argc,
3714                                       const char **argv)
3715 {
3716         if (c->display_usage) {
3717                 d_printf(  "%s\n"
3718                            "net rpc share migrate security\n"
3719                            "    %s\n",
3720                          _("Usage:"),
3721                          _("Migrate share-acls to local server"));
3722                 return 0;
3723         }
3724
3725         if (!c->opt_host) {
3726                 d_printf(_("no server to migrate\n"));
3727                 return -1;
3728         }
3729
3730         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
3731                                rpc_share_migrate_security_internals,
3732                                argc, argv);
3733 }
3734
3735 /**
3736  * Migrate shares (including share-definitions, share-acls and files with acls/attrs)
3737  * from one server to another.
3738  *
3739  * @param argc  Standard main() style argc.
3740  * @param argv  Standard main() style argv. Initial components are already
3741  *              stripped.
3742  *
3743  * @return A shell status integer (0 for success).
3744  *
3745  **/
3746 static int rpc_share_migrate_all(struct net_context *c, int argc,
3747                                  const char **argv)
3748 {
3749         int ret;
3750
3751         if (c->display_usage) {
3752                 d_printf(  "%s\n"
3753                            "net rpc share migrate all\n"
3754                            "    %s\n",
3755                          _("Usage:"),
3756                          _("Migrates shares including all share settings"));
3757                 return 0;
3758         }
3759
3760         if (!c->opt_host) {
3761                 d_printf(_("no server to migrate\n"));
3762                 return -1;
3763         }
3764
3765         /* order is important. we don't want to be locked out by the share-acl
3766          * before copying files - gd */
3767
3768         ret = run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
3769                               rpc_share_migrate_shares_internals, argc, argv);
3770         if (ret)
3771                 return ret;
3772
3773         ret = run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
3774                               rpc_share_migrate_files_internals, argc, argv);
3775         if (ret)
3776                 return ret;
3777
3778         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
3779                                rpc_share_migrate_security_internals, argc,
3780                                argv);
3781 }
3782
3783
3784 /**
3785  * 'net rpc share migrate' entrypoint.
3786  * @param argc  Standard main() style argc.
3787  * @param argv  Standard main() style argv. Initial components are already
3788  *              stripped.
3789  **/
3790 static int rpc_share_migrate(struct net_context *c, int argc, const char **argv)
3791 {
3792
3793         struct functable func[] = {
3794                 {
3795                         "all",
3796                         rpc_share_migrate_all,
3797                         NET_TRANSPORT_RPC,
3798                         N_("Migrate shares from remote to local server"),
3799                         N_("net rpc share migrate all\n"
3800                            "    Migrate shares from remote to local server")
3801                 },
3802                 {
3803                         "files",
3804                         rpc_share_migrate_files,
3805                         NET_TRANSPORT_RPC,
3806                         N_("Migrate files from remote to local server"),
3807                         N_("net rpc share migrate files\n"
3808                            "    Migrate files from remote to local server")
3809                 },
3810                 {
3811                         "security",
3812                         rpc_share_migrate_security,
3813                         NET_TRANSPORT_RPC,
3814                         N_("Migrate share-ACLs from remote to local server"),
3815                         N_("net rpc share migrate security\n"
3816                            "    Migrate share-ACLs from remote to local server")
3817                 },
3818                 {
3819                         "shares",
3820                         rpc_share_migrate_shares,
3821                         NET_TRANSPORT_RPC,
3822                         N_("Migrate shares from remote to local server"),
3823                         N_("net rpc share migrate shares\n"
3824                            "    Migrate shares from remote to local server")
3825                 },
3826                 {NULL, NULL, 0, NULL, NULL}
3827         };
3828
3829         net_mode_share = NET_MODE_SHARE_MIGRATE;
3830
3831         return net_run_function(c, argc, argv, "net rpc share migrate", func);
3832 }
3833
3834 struct full_alias {
3835         DOM_SID sid;
3836         uint32 num_members;
3837         DOM_SID *members;
3838 };
3839
3840 static int num_server_aliases;
3841 static struct full_alias *server_aliases;
3842
3843 /*
3844  * Add an alias to the static list.
3845  */
3846 static void push_alias(TALLOC_CTX *mem_ctx, struct full_alias *alias)
3847 {
3848         if (server_aliases == NULL)
3849                 server_aliases = SMB_MALLOC_ARRAY(struct full_alias, 100);
3850
3851         server_aliases[num_server_aliases] = *alias;
3852         num_server_aliases += 1;
3853 }
3854
3855 /*
3856  * For a specific domain on the server, fetch all the aliases
3857  * and their members. Add all of them to the server_aliases.
3858  */
3859
3860 static NTSTATUS rpc_fetch_domain_aliases(struct rpc_pipe_client *pipe_hnd,
3861                                         TALLOC_CTX *mem_ctx,
3862                                         struct policy_handle *connect_pol,
3863                                         const DOM_SID *domain_sid)
3864 {
3865         uint32 start_idx, max_entries, num_entries, i;
3866         struct samr_SamArray *groups = NULL;
3867         NTSTATUS result;
3868         struct policy_handle domain_pol;
3869
3870         /* Get domain policy handle */
3871
3872         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
3873                                         connect_pol,
3874                                         MAXIMUM_ALLOWED_ACCESS,
3875                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
3876                                         &domain_pol);
3877         if (!NT_STATUS_IS_OK(result))
3878                 return result;
3879
3880         start_idx = 0;
3881         max_entries = 250;
3882
3883         do {
3884                 result = rpccli_samr_EnumDomainAliases(pipe_hnd, mem_ctx,
3885                                                        &domain_pol,
3886                                                        &start_idx,
3887                                                        &groups,
3888                                                        max_entries,
3889                                                        &num_entries);
3890                 for (i = 0; i < num_entries; i++) {
3891
3892                         struct policy_handle alias_pol;
3893                         struct full_alias alias;
3894                         struct lsa_SidArray sid_array;
3895                         int j;
3896
3897                         result = rpccli_samr_OpenAlias(pipe_hnd, mem_ctx,
3898                                                        &domain_pol,
3899                                                        MAXIMUM_ALLOWED_ACCESS,
3900                                                        groups->entries[i].idx,
3901                                                        &alias_pol);
3902                         if (!NT_STATUS_IS_OK(result))
3903                                 goto done;
3904
3905                         result = rpccli_samr_GetMembersInAlias(pipe_hnd, mem_ctx,
3906                                                                &alias_pol,
3907                                                                &sid_array);
3908                         if (!NT_STATUS_IS_OK(result))
3909                                 goto done;
3910
3911                         alias.num_members = sid_array.num_sids;
3912
3913                         result = rpccli_samr_Close(pipe_hnd, mem_ctx, &alias_pol);
3914                         if (!NT_STATUS_IS_OK(result))
3915                                 goto done;
3916
3917                         alias.members = NULL;
3918
3919                         if (alias.num_members > 0) {
3920                                 alias.members = SMB_MALLOC_ARRAY(DOM_SID, alias.num_members);
3921
3922                                 for (j = 0; j < alias.num_members; j++)
3923                                         sid_copy(&alias.members[j],
3924                                                  sid_array.sids[j].sid);
3925                         }
3926
3927                         sid_compose(&alias.sid, domain_sid,
3928                                     groups->entries[i].idx);
3929
3930                         push_alias(mem_ctx, &alias);
3931                 }
3932         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
3933
3934         result = NT_STATUS_OK;
3935
3936  done:
3937         rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_pol);
3938
3939         return result;
3940 }
3941
3942 /*
3943  * Dump server_aliases as names for debugging purposes.
3944  */
3945
3946 static NTSTATUS rpc_aliaslist_dump(struct net_context *c,
3947                                 const DOM_SID *domain_sid,
3948                                 const char *domain_name,
3949                                 struct cli_state *cli,
3950                                 struct rpc_pipe_client *pipe_hnd,
3951                                 TALLOC_CTX *mem_ctx,
3952                                 int argc,
3953                                 const char **argv)
3954 {
3955         int i;
3956         NTSTATUS result;
3957         struct policy_handle lsa_pol;
3958
3959         result = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, true,
3960                                      SEC_FLAG_MAXIMUM_ALLOWED,
3961                                      &lsa_pol);
3962         if (!NT_STATUS_IS_OK(result))
3963                 return result;
3964
3965         for (i=0; i<num_server_aliases; i++) {
3966                 char **names;
3967                 char **domains;
3968                 enum lsa_SidType *types;
3969                 int j;
3970
3971                 struct full_alias *alias = &server_aliases[i];
3972
3973                 result = rpccli_lsa_lookup_sids(pipe_hnd, mem_ctx, &lsa_pol, 1,
3974                                              &alias->sid,
3975                                              &domains, &names, &types);
3976                 if (!NT_STATUS_IS_OK(result))
3977                         continue;
3978
3979                 DEBUG(1, ("%s\\%s %d: ", domains[0], names[0], types[0]));
3980
3981                 if (alias->num_members == 0) {
3982                         DEBUG(1, ("\n"));
3983                         continue;
3984                 }
3985
3986                 result = rpccli_lsa_lookup_sids(pipe_hnd, mem_ctx, &lsa_pol,
3987                                              alias->num_members,
3988                                              alias->members,
3989                                              &domains, &names, &types);
3990
3991                 if (!NT_STATUS_IS_OK(result) &&
3992                     !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED))
3993                         continue;
3994
3995                 for (j=0; j<alias->num_members; j++)
3996                         DEBUG(1, ("%s\\%s (%d); ",
3997                                   domains[j] ? domains[j] : "*unknown*", 
3998                                   names[j] ? names[j] : "*unknown*",types[j]));
3999                 DEBUG(1, ("\n"));
4000         }
4001
4002         rpccli_lsa_Close(pipe_hnd, mem_ctx, &lsa_pol);
4003
4004         return NT_STATUS_OK;
4005 }
4006
4007 /*
4008  * Fetch a list of all server aliases and their members into
4009  * server_aliases.
4010  */
4011
4012 static NTSTATUS rpc_aliaslist_internals(struct net_context *c,
4013                                         const DOM_SID *domain_sid,
4014                                         const char *domain_name,
4015                                         struct cli_state *cli,
4016                                         struct rpc_pipe_client *pipe_hnd,
4017                                         TALLOC_CTX *mem_ctx,
4018                                         int argc,
4019                                         const char **argv)
4020 {
4021         NTSTATUS result;
4022         struct policy_handle connect_pol;
4023
4024         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
4025                                       pipe_hnd->desthost,
4026                                       MAXIMUM_ALLOWED_ACCESS,
4027                                       &connect_pol);
4028
4029         if (!NT_STATUS_IS_OK(result))
4030                 goto done;
4031
4032         result = rpc_fetch_domain_aliases(pipe_hnd, mem_ctx, &connect_pol,
4033                                           &global_sid_Builtin);
4034
4035         if (!NT_STATUS_IS_OK(result))
4036                 goto done;
4037
4038         result = rpc_fetch_domain_aliases(pipe_hnd, mem_ctx, &connect_pol,
4039                                           domain_sid);
4040
4041         rpccli_samr_Close(pipe_hnd, mem_ctx, &connect_pol);
4042  done:
4043         return result;
4044 }
4045
4046 static void init_user_token(NT_USER_TOKEN *token, DOM_SID *user_sid)
4047 {
4048         token->num_sids = 4;
4049
4050         if (!(token->user_sids = SMB_MALLOC_ARRAY(DOM_SID, 4))) {
4051                 d_fprintf(stderr, "malloc %s\n",_("failed"));
4052                 token->num_sids = 0;
4053                 return;
4054         }
4055
4056         token->user_sids[0] = *user_sid;
4057         sid_copy(&token->user_sids[1], &global_sid_World);
4058         sid_copy(&token->user_sids[2], &global_sid_Network);
4059         sid_copy(&token->user_sids[3], &global_sid_Authenticated_Users);
4060 }
4061
4062 static void free_user_token(NT_USER_TOKEN *token)
4063 {
4064         SAFE_FREE(token->user_sids);
4065 }
4066
4067 static void add_sid_to_token(NT_USER_TOKEN *token, DOM_SID *sid)
4068 {
4069         if (is_sid_in_token(token, sid))
4070                 return;
4071
4072         token->user_sids = SMB_REALLOC_ARRAY(token->user_sids, DOM_SID, token->num_sids+1);
4073         if (!token->user_sids) {
4074                 return;
4075         }
4076
4077         sid_copy(&token->user_sids[token->num_sids], sid);
4078
4079         token->num_sids += 1;
4080 }
4081
4082 struct user_token {
4083         fstring name;
4084         NT_USER_TOKEN token;
4085 };
4086
4087 static void dump_user_token(struct user_token *token)
4088 {
4089         int i;
4090
4091         d_printf("%s\n", token->name);
4092
4093         for (i=0; i<token->token.num_sids; i++) {
4094                 d_printf(" %s\n", sid_string_tos(&token->token.user_sids[i]));
4095         }
4096 }
4097
4098 static bool is_alias_member(DOM_SID *sid, struct full_alias *alias)
4099 {
4100         int i;
4101
4102         for (i=0; i<alias->num_members; i++) {
4103                 if (sid_compare(sid, &alias->members[i]) == 0)
4104                         return true;
4105         }
4106
4107         return false;
4108 }
4109
4110 static void collect_sid_memberships(NT_USER_TOKEN *token, DOM_SID sid)
4111 {
4112         int i;
4113
4114         for (i=0; i<num_server_aliases; i++) {
4115                 if (is_alias_member(&sid, &server_aliases[i]))
4116                         add_sid_to_token(token, &server_aliases[i].sid);
4117         }
4118 }
4119
4120 /*
4121  * We got a user token with all the SIDs we can know about without asking the
4122  * server directly. These are the user and domain group sids. All of these can
4123  * be members of aliases. So scan the list of aliases for each of the SIDs and
4124  * add them to the token.
4125  */
4126
4127 static void collect_alias_memberships(NT_USER_TOKEN *token)
4128 {
4129         int num_global_sids = token->num_sids;
4130         int i;
4131
4132         for (i=0; i<num_global_sids; i++) {
4133                 collect_sid_memberships(token, token->user_sids[i]);
4134         }
4135 }
4136
4137 static bool get_user_sids(const char *domain, const char *user, NT_USER_TOKEN *token)
4138 {
4139         wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
4140         enum wbcSidType type;
4141         fstring full_name;
4142         struct wbcDomainSid wsid;
4143         char *sid_str = NULL;
4144         DOM_SID user_sid;
4145         uint32_t num_groups;
4146         gid_t *groups = NULL;
4147         uint32_t i;
4148
4149         fstr_sprintf(full_name, "%s%c%s",
4150                      domain, *lp_winbind_separator(), user);
4151
4152         /* First let's find out the user sid */
4153
4154         wbc_status = wbcLookupName(domain, user, &wsid, &type);
4155
4156         if (!WBC_ERROR_IS_OK(wbc_status)) {
4157                 DEBUG(1, ("winbind could not find %s: %s\n",
4158                           full_name, wbcErrorString(wbc_status)));
4159                 return false;
4160         }
4161
4162         wbc_status = wbcSidToString(&wsid, &sid_str);
4163         if (!WBC_ERROR_IS_OK(wbc_status)) {
4164                 return false;
4165         }
4166
4167         if (type != SID_NAME_USER) {
4168                 wbcFreeMemory(sid_str);
4169                 DEBUG(1, ("%s is not a user\n", full_name));
4170                 return false;
4171         }
4172
4173         if (!string_to_sid(&user_sid, sid_str)) {
4174                 DEBUG(1,("Could not convert sid %s from string\n", sid_str));
4175                 return false;
4176         }
4177
4178         wbcFreeMemory(sid_str);
4179         sid_str = NULL;
4180
4181         init_user_token(token, &user_sid);
4182
4183         /* And now the groups winbind knows about */
4184
4185         wbc_status = wbcGetGroups(full_name, &num_groups, &groups);
4186         if (!WBC_ERROR_IS_OK(wbc_status)) {
4187                 DEBUG(1, ("winbind could not get groups of %s: %s\n",
4188                         full_name, wbcErrorString(wbc_status)));
4189                 return false;
4190         }
4191
4192         for (i = 0; i < num_groups; i++) {
4193                 gid_t gid = groups[i];
4194                 DOM_SID sid;
4195
4196                 wbc_status = wbcGidToSid(gid, &wsid);
4197                 if (!WBC_ERROR_IS_OK(wbc_status)) {
4198                         DEBUG(1, ("winbind could not find SID of gid %u: %s\n",
4199                                   (unsigned int)gid, wbcErrorString(wbc_status)));
4200                         wbcFreeMemory(groups);
4201                         return false;
4202                 }
4203
4204                 wbc_status = wbcSidToString(&wsid, &sid_str);
4205                 if (!WBC_ERROR_IS_OK(wbc_status)) {
4206                         wbcFreeMemory(groups);
4207                         return false;
4208                 }
4209
4210                 DEBUG(3, (" %s\n", sid_str));
4211
4212                 string_to_sid(&sid, sid_str);
4213                 wbcFreeMemory(sid_str);
4214                 sid_str = NULL;
4215
4216                 add_sid_to_token(token, &sid);
4217         }
4218         wbcFreeMemory(groups);
4219
4220         return true;
4221 }
4222
4223 /**
4224  * Get a list of all user tokens we want to look at
4225  **/
4226
4227 static bool get_user_tokens(struct net_context *c, int *num_tokens,
4228                             struct user_token **user_tokens)
4229 {
4230         wbcErr wbc_status = WBC_ERR_UNKNOWN_FAILURE;
4231         uint32_t i, num_users;
4232         const char **users;
4233         struct user_token *result;
4234         TALLOC_CTX *frame = NULL;
4235
4236         if (lp_winbind_use_default_domain() &&
4237             (c->opt_target_workgroup == NULL)) {
4238                 d_fprintf(stderr, _("winbind use default domain = yes set, "
4239                          "please specify a workgroup\n"));
4240                 return false;
4241         }
4242
4243         /* Send request to winbind daemon */
4244
4245         wbc_status = wbcListUsers(NULL, &num_users, &users);
4246         if (!WBC_ERROR_IS_OK(wbc_status)) {
4247                 DEBUG(1, (_("winbind could not list users: %s\n"),
4248                           wbcErrorString(wbc_status)));
4249                 return false;
4250         }
4251
4252         result = SMB_MALLOC_ARRAY(struct user_token, num_users);
4253
4254         if (result == NULL) {
4255                 DEBUG(1, ("Could not malloc sid array\n"));
4256                 wbcFreeMemory(users);
4257                 return false;
4258         }
4259
4260         frame = talloc_stackframe();
4261         for (i=0; i < num_users; i++) {
4262                 fstring domain, user;
4263                 char *p;
4264
4265                 fstrcpy(result[i].name, users[i]);
4266
4267                 p = strchr(users[i], *lp_winbind_separator());
4268
4269                 DEBUG(3, ("%s\n", users[i]));
4270
4271                 if (p == NULL) {
4272                         fstrcpy(domain, c->opt_target_workgroup);
4273                         fstrcpy(user, users[i]);
4274                 } else {
4275                         *p++ = '\0';
4276                         fstrcpy(domain, users[i]);
4277                         strupper_m(domain);
4278                         fstrcpy(user, p);
4279                 }
4280
4281                 get_user_sids(domain, user, &(result[i].token));
4282                 i+=1;
4283         }
4284         TALLOC_FREE(frame);
4285         wbcFreeMemory(users);
4286
4287         *num_tokens = num_users;
4288         *user_tokens = result;
4289
4290         return true;
4291 }
4292
4293 static bool get_user_tokens_from_file(FILE *f,
4294                                       int *num_tokens,
4295                                       struct user_token **tokens)
4296 {
4297         struct user_token *token = NULL;
4298
4299         while (!feof(f)) {
4300                 fstring line;
4301
4302                 if (fgets(line, sizeof(line)-1, f) == NULL) {
4303                         return true;
4304                 }
4305
4306                 if ((strlen(line) > 0) && (line[strlen(line)-1] == '\n')) {
4307                         line[strlen(line)-1] = '\0';
4308                 }
4309
4310                 if (line[0] == ' ') {
4311                         /* We have a SID */
4312
4313                         DOM_SID sid;
4314                         if(!string_to_sid(&sid, &line[1])) {
4315                                 DEBUG(1,("get_user_tokens_from_file: Could "
4316                                         "not convert sid %s \n",&line[1]));
4317                                 return false;
4318                         }
4319
4320                         if (token == NULL) {
4321                                 DEBUG(0, ("File does not begin with username"));
4322                                 return false;
4323                         }
4324
4325                         add_sid_to_token(&token->token, &sid);
4326                         continue;
4327                 }
4328
4329                 /* And a new user... */
4330
4331                 *num_tokens += 1;
4332                 *tokens = SMB_REALLOC_ARRAY(*tokens, struct user_token, *num_tokens);
4333                 if (*tokens == NULL) {
4334                         DEBUG(0, ("Could not realloc tokens\n"));
4335                         return false;
4336                 }
4337
4338                 token = &((*tokens)[*num_tokens-1]);
4339
4340                 fstrcpy(token->name, line);
4341                 token->token.num_sids = 0;
4342                 token->token.user_sids = NULL;
4343                 continue;
4344         }
4345         
4346         return false;
4347 }
4348
4349
4350 /*
4351  * Show the list of all users that have access to a share
4352  */
4353
4354 static void show_userlist(struct rpc_pipe_client *pipe_hnd,
4355                         TALLOC_CTX *mem_ctx,
4356                         const char *netname,
4357                         int num_tokens,
4358                         struct user_token *tokens)
4359 {
4360         uint16_t fnum;
4361         SEC_DESC *share_sd = NULL;
4362         SEC_DESC *root_sd = NULL;
4363         struct cli_state *cli = rpc_pipe_np_smb_conn(pipe_hnd);
4364         int i;
4365         union srvsvc_NetShareInfo info;
4366         WERROR result;
4367         NTSTATUS status;
4368         uint16 cnum;
4369
4370         status = rpccli_srvsvc_NetShareGetInfo(pipe_hnd, mem_ctx,
4371                                                pipe_hnd->desthost,
4372                                                netname,
4373                                                502,
4374                                                &info,
4375                                                &result);
4376
4377         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(result)) {
4378                 DEBUG(1, ("Coult not query secdesc for share %s\n",
4379                           netname));
4380                 return;
4381         }
4382
4383         share_sd = info.info502->sd_buf.sd;
4384         if (share_sd == NULL) {
4385                 DEBUG(1, ("Got no secdesc for share %s\n",
4386                           netname));
4387         }
4388
4389         cnum = cli->cnum;
4390
4391         if (!NT_STATUS_IS_OK(cli_tcon_andx(cli, netname, "A:", "", 0))) {
4392                 return;
4393         }
4394
4395         if (!NT_STATUS_IS_OK(cli_ntcreate(cli, "\\", 0, READ_CONTROL_ACCESS, 0,
4396                         FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN, 0x0, 0x0, &fnum))) {
4397                 root_sd = cli_query_secdesc(cli, fnum, mem_ctx);
4398         }
4399
4400         for (i=0; i<num_tokens; i++) {
4401                 uint32 acc_granted;
4402
4403                 if (share_sd != NULL) {
4404                         status = se_access_check(share_sd, &tokens[i].token,
4405                                              1, &acc_granted);
4406
4407                         if (!NT_STATUS_IS_OK(status)) {
4408                                 DEBUG(1, ("Could not check share_sd for "
4409                                           "user %s\n",
4410                                           tokens[i].name));
4411                                 continue;
4412                         }
4413                 }
4414
4415                 if (root_sd == NULL) {
4416                         d_printf(" %s\n", tokens[i].name);
4417                         continue;
4418                 }
4419
4420                 status = se_access_check(root_sd, &tokens[i].token,
4421                                      1, &acc_granted);
4422                 if (!NT_STATUS_IS_OK(status)) {
4423                         DEBUG(1, ("Could not check root_sd for user %s\n",
4424                                   tokens[i].name));
4425                         continue;
4426                 }
4427                 d_printf(" %s\n", tokens[i].name);
4428         }
4429
4430         if (fnum != (uint16_t)-1)
4431                 cli_close(cli, fnum);
4432         cli_tdis(cli);
4433         cli->cnum = cnum;
4434         
4435         return;
4436 }
4437
4438 struct share_list {
4439         int num_shares;
4440         char **shares;
4441 };
4442
4443 static void collect_share(const char *name, uint32 m,
4444                           const char *comment, void *state)
4445 {
4446         struct share_list *share_list = (struct share_list *)state;
4447
4448         if (m != STYPE_DISKTREE)
4449                 return;
4450
4451         share_list->num_shares += 1;
4452         share_list->shares = SMB_REALLOC_ARRAY(share_list->shares, char *, share_list->num_shares);
4453         if (!share_list->shares) {
4454                 share_list->num_shares = 0;
4455                 return;
4456         }
4457         share_list->shares[share_list->num_shares-1] = SMB_STRDUP(name);
4458 }
4459
4460 /**
4461  * List shares on a remote RPC server, including the security descriptors.
4462  *
4463  * All parameters are provided by the run_rpc_command function, except for
4464  * argc, argv which are passed through.
4465  *
4466  * @param domain_sid The domain sid acquired from the remote server.
4467  * @param cli A cli_state connected to the server.
4468  * @param mem_ctx Talloc context, destroyed on completion of the function.
4469  * @param argc  Standard main() style argc.
4470  * @param argv  Standard main() style argv. Initial components are already
4471  *              stripped.
4472  *
4473  * @return Normal NTSTATUS return.
4474  **/
4475
4476 static NTSTATUS rpc_share_allowedusers_internals(struct net_context *c,
4477                                                 const DOM_SID *domain_sid,
4478                                                 const char *domain_name,
4479                                                 struct cli_state *cli,
4480                                                 struct rpc_pipe_client *pipe_hnd,
4481                                                 TALLOC_CTX *mem_ctx,
4482                                                 int argc,
4483                                                 const char **argv)
4484 {
4485         int ret;
4486         bool r;
4487         uint32 i;
4488         FILE *f;
4489
4490         struct user_token *tokens = NULL;
4491         int num_tokens = 0;
4492
4493         struct share_list share_list;
4494
4495         if (argc == 0) {
4496                 f = stdin;
4497         } else {
4498                 f = fopen(argv[0], "r");
4499         }
4500
4501         if (f == NULL) {
4502                 DEBUG(0, ("Could not open userlist: %s\n", strerror(errno)));
4503                 return NT_STATUS_UNSUCCESSFUL;
4504         }
4505
4506         r = get_user_tokens_from_file(f, &num_tokens, &tokens);
4507
4508         if (f != stdin)
4509                 fclose(f);
4510
4511         if (!r) {
4512                 DEBUG(0, ("Could not read users from file\n"));
4513                 return NT_STATUS_UNSUCCESSFUL;
4514         }
4515
4516         for (i=0; i<num_tokens; i++)
4517                 collect_alias_memberships(&tokens[i].token);
4518
4519         share_list.num_shares = 0;
4520         share_list.shares = NULL;
4521
4522         ret = cli_RNetShareEnum(cli, collect_share, &share_list);
4523
4524         if (ret == -1) {
4525                 DEBUG(0, ("Error returning browse list: %s\n",
4526                           cli_errstr(cli)));
4527                 goto done;
4528         }
4529
4530         for (i = 0; i < share_list.num_shares; i++) {
4531                 char *netname = share_list.shares[i];
4532
4533                 if (netname[strlen(netname)-1] == '$')
4534                         continue;
4535
4536                 d_printf("%s\n", netname);
4537
4538                 show_userlist(pipe_hnd, mem_ctx, netname,
4539                               num_tokens, tokens);
4540         }
4541  done:
4542         for (i=0; i<num_tokens; i++) {
4543                 free_user_token(&tokens[i].token);
4544         }
4545         SAFE_FREE(tokens);
4546         SAFE_FREE(share_list.shares);
4547
4548         return NT_STATUS_OK;
4549 }
4550
4551 static int rpc_share_allowedusers(struct net_context *c, int argc,
4552                                   const char **argv)
4553 {
4554         int result;
4555
4556         if (c->display_usage) {
4557                 d_printf(  "%s\n"
4558                            "net rpc share allowedusers\n"
4559                             "    %s\n",
4560                           _("Usage:"),
4561                           _("List allowed users"));
4562                 return 0;
4563         }
4564
4565         result = run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
4566                                  rpc_aliaslist_internals,
4567                                  argc, argv);
4568         if (result != 0)
4569                 return result;
4570
4571         result = run_rpc_command(c, NULL, &ndr_table_lsarpc.syntax_id, 0,
4572                                  rpc_aliaslist_dump,
4573                                  argc, argv);
4574         if (result != 0)
4575                 return result;
4576
4577         return run_rpc_command(c, NULL, &ndr_table_srvsvc.syntax_id, 0,
4578                                rpc_share_allowedusers_internals,
4579                                argc, argv);
4580 }
4581
4582 int net_usersidlist(struct net_context *c, int argc, const char **argv)
4583 {
4584         int num_tokens = 0;
4585         struct user_token *tokens = NULL;
4586         int i;
4587
4588         if (argc != 0) {
4589                 net_usersidlist_usage(c, argc, argv);
4590                 return 0;
4591         }
4592
4593         if (!get_user_tokens(c, &num_tokens, &tokens)) {
4594                 DEBUG(0, ("Could not get the user/sid list\n"));
4595                 return 0;
4596         }
4597
4598         for (i=0; i<num_tokens; i++) {
4599                 dump_user_token(&tokens[i]);
4600                 free_user_token(&tokens[i].token);
4601         }
4602
4603         SAFE_FREE(tokens);
4604         return 1;
4605 }
4606
4607 int net_usersidlist_usage(struct net_context *c, int argc, const char **argv)
4608 {
4609         d_printf(_("net usersidlist\n"
4610                    "\tprints out a list of all users the running winbind knows\n"
4611                    "\tabout, together with all their SIDs. This is used as\n"
4612                    "\tinput to the 'net rpc share allowedusers' command.\n\n"));
4613
4614         net_common_flags_usage(c, argc, argv);
4615         return -1;
4616 }
4617
4618 /**
4619  * 'net rpc share' entrypoint.
4620  * @param argc  Standard main() style argc.
4621  * @param argv  Standard main() style argv. Initial components are already
4622  *              stripped.
4623  **/
4624
4625 int net_rpc_share(struct net_context *c, int argc, const char **argv)
4626 {
4627         NET_API_STATUS status;
4628
4629         struct functable func[] = {
4630                 {
4631                         "add",
4632                         rpc_share_add,
4633                         NET_TRANSPORT_RPC,
4634                         N_("Add share"),
4635                         N_("net rpc share add\n"
4636                            "    Add share")
4637                 },
4638                 {
4639                         "delete",
4640                         rpc_share_delete,
4641                         NET_TRANSPORT_RPC,
4642                         N_("Remove share"),
4643                         N_("net rpc share delete\n"
4644                            "    Remove share")
4645                 },
4646                 {
4647                         "allowedusers",
4648                         rpc_share_allowedusers,
4649                         NET_TRANSPORT_RPC,
4650                         N_("Modify allowed users"),
4651                         N_("net rpc share allowedusers\n"
4652                            "    Modify allowed users")
4653                 },
4654                 {
4655                         "migrate",
4656                         rpc_share_migrate,
4657                         NET_TRANSPORT_RPC,
4658                         N_("Migrate share to local server"),
4659                         N_("net rpc share migrate\n"
4660                            "    Migrate share to local server")
4661                 },
4662                 {
4663                         "list",
4664                         rpc_share_list,
4665                         NET_TRANSPORT_RPC,
4666                         N_("List shares"),
4667                         N_("net rpc share list\n"
4668                            "    List shares")
4669                 },
4670                 {NULL, NULL, 0, NULL, NULL}
4671         };
4672
4673         status = libnetapi_init(&c->netapi_ctx);
4674         if (status != 0) {
4675                 return -1;
4676         }
4677         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
4678         libnetapi_set_password(c->netapi_ctx, c->opt_password);
4679         if (c->opt_kerberos) {
4680                 libnetapi_set_use_kerberos(c->netapi_ctx);
4681         }
4682
4683         if (argc == 0) {
4684                 if (c->display_usage) {
4685                         d_printf("%s\n%s",
4686                                  _("Usage:"),
4687                                  _("net rpc share\n"
4688                                    "    List shares\n"
4689                                    "    Alias for net rpc share list\n"));
4690                         net_display_usage_from_functable(func);
4691                         return 0;
4692                 }
4693
4694                 return rpc_share_list(c, argc, argv);
4695         }
4696
4697         return net_run_function(c, argc, argv, "net rpc share", func);
4698 }
4699
4700 static NTSTATUS rpc_sh_share_list(struct net_context *c,
4701                                   TALLOC_CTX *mem_ctx,
4702                                   struct rpc_sh_ctx *ctx,
4703                                   struct rpc_pipe_client *pipe_hnd,
4704                                   int argc, const char **argv)
4705 {
4706
4707         return werror_to_ntstatus(W_ERROR(rpc_share_list(c, argc, argv)));
4708 }
4709
4710 static NTSTATUS rpc_sh_share_add(struct net_context *c,
4711                                  TALLOC_CTX *mem_ctx,
4712                                  struct rpc_sh_ctx *ctx,
4713                                  struct rpc_pipe_client *pipe_hnd,
4714                                  int argc, const char **argv)
4715 {
4716         NET_API_STATUS status;
4717         uint32_t parm_err = 0;
4718         struct SHARE_INFO_2 i2;
4719
4720         if ((argc < 2) || (argc > 3)) {
4721                 d_fprintf(stderr, _("Usage: %s <share> <path> [comment]\n"),
4722                           ctx->whoami);
4723                 return NT_STATUS_INVALID_PARAMETER;
4724         }
4725
4726         i2.shi2_netname         = argv[0];
4727         i2.shi2_type            = STYPE_DISKTREE;
4728         i2.shi2_remark          = (argc == 3) ? argv[2] : "";
4729         i2.shi2_permissions     = 0;
4730         i2.shi2_max_uses        = 0;
4731         i2.shi2_current_uses    = 0;
4732         i2.shi2_path            = argv[1];
4733         i2.shi2_passwd          = NULL;
4734
4735         status = NetShareAdd(pipe_hnd->desthost,
4736                              2,
4737                              (uint8_t *)&i2,
4738                              &parm_err);
4739
4740         return werror_to_ntstatus(W_ERROR(status));
4741 }
4742
4743 static NTSTATUS rpc_sh_share_delete(struct net_context *c,
4744                                     TALLOC_CTX *mem_ctx,
4745                                     struct rpc_sh_ctx *ctx,
4746                                     struct rpc_pipe_client *pipe_hnd,
4747                                     int argc, const char **argv)
4748 {
4749         if (argc != 1) {
4750                 d_fprintf(stderr, "%s %s <share>\n", _("Usage:"), ctx->whoami);
4751                 return NT_STATUS_INVALID_PARAMETER;
4752         }
4753
4754         return werror_to_ntstatus(W_ERROR(NetShareDel(pipe_hnd->desthost, argv[0], 0)));
4755 }
4756
4757 static NTSTATUS rpc_sh_share_info(struct net_context *c,
4758                                   TALLOC_CTX *mem_ctx,
4759                                   struct rpc_sh_ctx *ctx,
4760                                   struct rpc_pipe_client *pipe_hnd,
4761                                   int argc, const char **argv)
4762 {
4763         union srvsvc_NetShareInfo info;
4764         WERROR result;
4765         NTSTATUS status;
4766
4767         if (argc != 1) {
4768                 d_fprintf(stderr, "%s %s <share>\n", _("Usage:"), ctx->whoami);
4769                 return NT_STATUS_INVALID_PARAMETER;
4770         }
4771
4772         status = rpccli_srvsvc_NetShareGetInfo(pipe_hnd, mem_ctx,
4773                                                pipe_hnd->desthost,
4774                                                argv[0],
4775                                                2,
4776                                                &info,
4777                                                &result);
4778         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(result)) {
4779                 goto done;
4780         }
4781
4782         d_printf(_("Name:     %s\n"), info.info2->name);
4783         d_printf(_("Comment:  %s\n"), info.info2->comment);
4784         d_printf(_("Path:     %s\n"), info.info2->path);
4785         d_printf(_("Password: %s\n"), info.info2->password);
4786
4787  done:
4788         return werror_to_ntstatus(result);
4789 }
4790
4791 struct rpc_sh_cmd *net_rpc_share_cmds(struct net_context *c, TALLOC_CTX *mem_ctx,
4792                                       struct rpc_sh_ctx *ctx)
4793 {
4794         static struct rpc_sh_cmd cmds[] = {
4795
4796         { "list", NULL, &ndr_table_srvsvc.syntax_id, rpc_sh_share_list,
4797           N_("List available shares") },
4798
4799         { "add", NULL, &ndr_table_srvsvc.syntax_id, rpc_sh_share_add,
4800           N_("Add a share") },
4801
4802         { "delete", NULL, &ndr_table_srvsvc.syntax_id, rpc_sh_share_delete,
4803           N_("Delete a share") },
4804
4805         { "info", NULL, &ndr_table_srvsvc.syntax_id, rpc_sh_share_info,
4806           N_("Get information about a share") },
4807
4808         { NULL, NULL, 0, NULL, NULL }
4809         };
4810
4811         return cmds;
4812 }
4813
4814 /****************************************************************************/
4815
4816 static int rpc_file_usage(struct net_context *c, int argc, const char **argv)
4817 {
4818         return net_file_usage(c, argc, argv);
4819 }
4820
4821 /**
4822  * Close a file on a remote RPC server.
4823  *
4824  * @param argc  Standard main() style argc.
4825  * @param argv  Standard main() style argv. Initial components are already
4826  *              stripped.
4827  *
4828  * @return A shell status integer (0 for success).
4829  **/
4830 static int rpc_file_close(struct net_context *c, int argc, const char **argv)
4831 {
4832         if (argc < 1 || c->display_usage) {
4833                 return rpc_file_usage(c, argc, argv);
4834         }
4835
4836         return NetFileClose(c->opt_host, atoi(argv[0]));
4837 }
4838
4839 /**
4840  * Formatted print of open file info
4841  *
4842  * @param r  struct FILE_INFO_3 contents
4843  **/
4844
4845 static void display_file_info_3(struct FILE_INFO_3 *r)
4846 {
4847         d_printf("%-7.1d %-20.20s 0x%-4.2x %-6.1d %s\n",
4848                  r->fi3_id, r->fi3_username, r->fi3_permissions,
4849                  r->fi3_num_locks, r->fi3_pathname);
4850 }
4851
4852 /**
4853  * List files for a user on a remote RPC server.
4854  *
4855  * @param argc  Standard main() style argc.
4856  * @param argv  Standard main() style argv. Initial components are already
4857  *              stripped.
4858  *
4859  * @return A shell status integer (0 for success)..
4860  **/
4861
4862 static int rpc_file_user(struct net_context *c, int argc, const char **argv)
4863 {
4864         NET_API_STATUS status;
4865         uint32 preferred_len = 0xffffffff, i;
4866         const char *username=NULL;
4867         uint32_t total_entries = 0;
4868         uint32_t entries_read = 0;
4869         uint32_t resume_handle = 0;
4870         struct FILE_INFO_3 *i3 = NULL;
4871
4872         if (c->display_usage) {
4873                 return rpc_file_usage(c, argc, argv);
4874         }
4875
4876         /* if argc > 0, must be user command */
4877         if (argc > 0) {
4878                 username = smb_xstrdup(argv[0]);
4879         }
4880
4881         status = NetFileEnum(c->opt_host,
4882                              NULL,
4883                              username,
4884                              3,
4885                              (uint8_t **)(void *)&i3,
4886                              preferred_len,
4887                              &entries_read,
4888                              &total_entries,
4889                              &resume_handle);
4890
4891         if (status != 0) {
4892                 goto done;
4893         }
4894
4895         /* Display results */
4896
4897         d_printf(_(
4898                  "\nEnumerating open files on remote server:\n\n"
4899                  "\nFileId  Opened by            Perms  Locks  Path"
4900                  "\n------  ---------            -----  -----  ---- \n"));
4901         for (i = 0; i < entries_read; i++) {
4902                 display_file_info_3(&i3[i]);
4903         }
4904  done:
4905         return status;
4906 }
4907
4908 /**
4909  * 'net rpc file' entrypoint.
4910  * @param argc  Standard main() style argc.
4911  * @param argv  Standard main() style argv. Initial components are already
4912  *              stripped.
4913  **/
4914
4915 int net_rpc_file(struct net_context *c, int argc, const char **argv)
4916 {
4917         NET_API_STATUS status;
4918
4919         struct functable func[] = {
4920                 {
4921                         "close",
4922                         rpc_file_close,
4923                         NET_TRANSPORT_RPC,
4924                         N_("Close opened file"),
4925                         N_("net rpc file close\n"
4926                            "    Close opened file")
4927                 },
4928                 {
4929                         "user",
4930                         rpc_file_user,
4931                         NET_TRANSPORT_RPC,
4932                         N_("List files opened by user"),
4933                         N_("net rpc file user\n"
4934                            "    List files opened by user")
4935                 },
4936 #if 0
4937                 {
4938                         "info",
4939                         rpc_file_info,
4940                         NET_TRANSPORT_RPC,
4941                         N_("Display information about opened file"),
4942                         N_("net rpc file info\n"
4943                            "    Display information about opened file")
4944                 },
4945 #endif
4946                 {NULL, NULL, 0, NULL, NULL}
4947         };
4948
4949         status = libnetapi_init(&c->netapi_ctx);
4950         if (status != 0) {
4951                 return -1;
4952         }
4953         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
4954         libnetapi_set_password(c->netapi_ctx, c->opt_password);
4955         if (c->opt_kerberos) {
4956                 libnetapi_set_use_kerberos(c->netapi_ctx);
4957         }
4958
4959         if (argc == 0) {
4960                 if (c->display_usage) {
4961                         d_printf(_("Usage:\n"));
4962                         d_printf(_("net rpc file\n"
4963                                    "    List opened files\n"));
4964                         net_display_usage_from_functable(func);
4965                         return 0;
4966                 }
4967
4968                 return rpc_file_user(c, argc, argv);
4969         }
4970
4971         return net_run_function(c, argc, argv, "net rpc file", func);
4972 }
4973
4974 /**
4975  * ABORT the shutdown of a remote RPC Server, over initshutdown pipe.
4976  *
4977  * All parameters are provided by the run_rpc_command function, except for
4978  * argc, argv which are passed through.
4979  *
4980  * @param c     A net_context structure.
4981  * @param domain_sid The domain sid acquired from the remote server.
4982  * @param cli A cli_state connected to the server.
4983  * @param mem_ctx Talloc context, destroyed on completion of the function.
4984  * @param argc  Standard main() style argc.
4985  * @param argv  Standard main() style argv. Initial components are already
4986  *              stripped.
4987  *
4988  * @return Normal NTSTATUS return.
4989  **/
4990
4991 static NTSTATUS rpc_shutdown_abort_internals(struct net_context *c,
4992                                         const DOM_SID *domain_sid,
4993                                         const char *domain_name,
4994                                         struct cli_state *cli,
4995                                         struct rpc_pipe_client *pipe_hnd,
4996                                         TALLOC_CTX *mem_ctx,
4997                                         int argc,
4998                                         const char **argv)
4999 {
5000         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
5001
5002         result = rpccli_initshutdown_Abort(pipe_hnd, mem_ctx, NULL, NULL);
5003
5004         if (NT_STATUS_IS_OK(result)) {
5005                 d_printf(_("\nShutdown successfully aborted\n"));
5006                 DEBUG(5,("cmd_shutdown_abort: query succeeded\n"));
5007         } else
5008                 DEBUG(5,("cmd_shutdown_abort: query failed\n"));
5009
5010         return result;
5011 }
5012
5013 /**
5014  * ABORT the shutdown of a remote RPC Server, over winreg pipe.
5015  *
5016  * All parameters are provided by the run_rpc_command function, except for
5017  * argc, argv which are passed through.
5018  *
5019  * @param c     A net_context structure.
5020  * @param domain_sid The domain sid acquired from the remote server.
5021  * @param cli A cli_state connected to the server.
5022  * @param mem_ctx Talloc context, destroyed on completion of the function.
5023  * @param argc  Standard main() style argc.
5024  * @param argv  Standard main() style argv. Initial components are already
5025  *              stripped.
5026  *
5027  * @return Normal NTSTATUS return.
5028  **/
5029
5030 static NTSTATUS rpc_reg_shutdown_abort_internals(struct net_context *c,
5031                                                 const DOM_SID *domain_sid,
5032                                                 const char *domain_name,
5033                                                 struct cli_state *cli,
5034                                                 struct rpc_pipe_client *pipe_hnd,
5035                                                 TALLOC_CTX *mem_ctx,
5036                                                 int argc,
5037                                                 const char **argv)
5038 {
5039         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
5040
5041         result = rpccli_winreg_AbortSystemShutdown(pipe_hnd, mem_ctx, NULL, NULL);
5042
5043         if (NT_STATUS_IS_OK(result)) {
5044                 d_printf(_("\nShutdown successfully aborted\n"));
5045                 DEBUG(5,("cmd_reg_abort_shutdown: query succeeded\n"));
5046         } else
5047                 DEBUG(5,("cmd_reg_abort_shutdown: query failed\n"));
5048
5049         return result;
5050 }
5051
5052 /**
5053  * ABORT the shutdown of a remote RPC server.
5054  *
5055  * @param argc  Standard main() style argc.
5056  * @param argv  Standard main() style argv. Initial components are already
5057  *              stripped.
5058  *
5059  * @return A shell status integer (0 for success).
5060  **/
5061
5062 static int rpc_shutdown_abort(struct net_context *c, int argc,
5063                               const char **argv)
5064 {
5065         int rc = -1;
5066
5067         if (c->display_usage) {
5068                 d_printf(  "%s\n"
5069                            "net rpc abortshutdown\n"
5070                            "    %s\n",
5071                          _("Usage:"),
5072                          _("Abort a scheduled shutdown"));
5073                 return 0;
5074         }
5075
5076         rc = run_rpc_command(c, NULL, &ndr_table_initshutdown.syntax_id, 0,
5077                              rpc_shutdown_abort_internals, argc, argv);
5078
5079         if (rc == 0)
5080                 return rc;
5081
5082         DEBUG(1, ("initshutdown pipe didn't work, trying winreg pipe\n"));
5083
5084         return run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
5085                                rpc_reg_shutdown_abort_internals,
5086                                argc, argv);
5087 }
5088
5089 /**
5090  * Shut down a remote RPC Server via initshutdown pipe.
5091  *
5092  * All parameters are provided by the run_rpc_command function, except for
5093  * argc, argv which are passed through.
5094  *
5095  * @param c     A net_context structure.
5096  * @param domain_sid The domain sid acquired from the remote server.
5097  * @param cli A cli_state connected to the server.
5098  * @param mem_ctx Talloc context, destroyed on completion of the function.
5099  * @param argc  Standard main() style argc.
5100  * @param argv  Standard main() style argv. Initial components are already
5101  *              stripped.
5102  *
5103  * @return Normal NTSTATUS return.
5104  **/
5105
5106 NTSTATUS rpc_init_shutdown_internals(struct net_context *c,
5107                                      const DOM_SID *domain_sid,
5108                                      const char *domain_name,
5109                                      struct cli_state *cli,
5110                                      struct rpc_pipe_client *pipe_hnd,
5111                                      TALLOC_CTX *mem_ctx,
5112                                      int argc,
5113                                      const char **argv)
5114 {
5115         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
5116         const char *msg = N_("This machine will be shutdown shortly");
5117         uint32 timeout = 20;
5118         struct lsa_StringLarge msg_string;
5119
5120         if (c->opt_comment) {
5121                 msg = c->opt_comment;
5122         }
5123         if (c->opt_timeout) {
5124                 timeout = c->opt_timeout;
5125         }
5126
5127         msg_string.string = msg;
5128
5129         /* create an entry */
5130         result = rpccli_initshutdown_Init(pipe_hnd, mem_ctx, NULL,
5131                         &msg_string, timeout, c->opt_force, c->opt_reboot,
5132                         NULL);
5133
5134         if (NT_STATUS_IS_OK(result)) {
5135                 d_printf(_("\nShutdown of remote machine succeeded\n"));
5136                 DEBUG(5,("Shutdown of remote machine succeeded\n"));
5137         } else {
5138                 DEBUG(1,("Shutdown of remote machine failed!\n"));
5139         }
5140         return result;
5141 }
5142
5143 /**
5144  * Shut down a remote RPC Server via winreg pipe.
5145  *
5146  * All parameters are provided by the run_rpc_command function, except for
5147  * argc, argv which are passed through.
5148  *
5149  * @param c     A net_context structure.
5150  * @param domain_sid The domain sid acquired from the remote server.
5151  * @param cli A cli_state connected to the server.
5152  * @param mem_ctx Talloc context, destroyed on completion of the function.
5153  * @param argc  Standard main() style argc.
5154  * @param argv  Standard main() style argv. Initial components are already
5155  *              stripped.
5156  *
5157  * @return Normal NTSTATUS return.
5158  **/
5159
5160 NTSTATUS rpc_reg_shutdown_internals(struct net_context *c,
5161                                     const DOM_SID *domain_sid,
5162                                     const char *domain_name,
5163                                     struct cli_state *cli,
5164                                     struct rpc_pipe_client *pipe_hnd,
5165                                     TALLOC_CTX *mem_ctx,
5166                                     int argc,
5167                                     const char **argv)
5168 {
5169         const char *msg = N_("This machine will be shutdown shortly");
5170         uint32 timeout = 20;
5171         struct lsa_StringLarge msg_string;
5172         NTSTATUS result;
5173         WERROR werr;
5174
5175         if (c->opt_comment) {
5176                 msg = c->opt_comment;
5177         }
5178         msg_string.string = msg;
5179
5180         if (c->opt_timeout) {
5181                 timeout = c->opt_timeout;
5182         }
5183
5184         /* create an entry */
5185         result = rpccli_winreg_InitiateSystemShutdown(pipe_hnd, mem_ctx, NULL,
5186                         &msg_string, timeout, c->opt_force, c->opt_reboot,
5187                         &werr);
5188
5189         if (NT_STATUS_IS_OK(result)) {
5190                 d_printf(_("\nShutdown of remote machine succeeded\n"));
5191         } else {
5192                 d_fprintf(stderr, "\nShutdown of remote machine failed\n");
5193                 if ( W_ERROR_EQUAL(werr, WERR_MACHINE_LOCKED) )
5194                         d_fprintf(stderr, "\nMachine locked, use -f switch to force\n");
5195                 else
5196                         d_fprintf(stderr, "\nresult was: %s\n", win_errstr(werr));
5197         }
5198
5199         return result;
5200 }
5201
5202 /**
5203  * Shut down a remote RPC server.
5204  *
5205  * @param argc  Standard main() style argc.
5206  * @param argv  Standard main() style argv. Initial components are already
5207  *              stripped.
5208  *
5209  * @return A shell status integer (0 for success).
5210  **/
5211
5212 static int rpc_shutdown(struct net_context *c, int argc, const char **argv)
5213 {
5214         int rc =  -1;
5215
5216         if (c->display_usage) {
5217                 d_printf(  "%s\n"
5218                            "net rpc shutdown\n"
5219                            "    %s\n",
5220                          _("Usage:"),
5221                          _("Shut down a remote RPC server"));
5222                 return 0;
5223         }
5224
5225         rc = run_rpc_command(c, NULL, &ndr_table_initshutdown.syntax_id, 0,
5226                              rpc_init_shutdown_internals, argc, argv);
5227
5228         if (rc) {
5229                 DEBUG(1, ("initshutdown pipe failed, trying winreg pipe\n"));
5230                 rc = run_rpc_command(c, NULL, &ndr_table_winreg.syntax_id, 0,
5231                                      rpc_reg_shutdown_internals, argc, argv);
5232         }
5233
5234         return rc;
5235 }
5236
5237 /***************************************************************************
5238   NT Domain trusts code (i.e. 'net rpc trustdom' functionality)
5239  ***************************************************************************/
5240
5241 /**
5242  * Add interdomain trust account to the RPC server.
5243  * All parameters (except for argc and argv) are passed by run_rpc_command
5244  * function.
5245  *
5246  * @param c     A net_context structure.
5247  * @param domain_sid The domain sid acquired from the server.
5248  * @param cli A cli_state connected to the server.
5249  * @param mem_ctx Talloc context, destroyed on completion of the function.
5250  * @param argc  Standard main() style argc.
5251  * @param argv  Standard main() style argv. Initial components are already
5252  *              stripped.
5253  *
5254  * @return normal NTSTATUS return code.
5255  */
5256
5257 static NTSTATUS rpc_trustdom_add_internals(struct net_context *c,
5258                                                 const DOM_SID *domain_sid,
5259                                                 const char *domain_name,
5260                                                 struct cli_state *cli,
5261                                                 struct rpc_pipe_client *pipe_hnd,
5262                                                 TALLOC_CTX *mem_ctx,
5263                                                 int argc,
5264                                                 const char **argv)
5265 {
5266         struct policy_handle connect_pol, domain_pol, user_pol;
5267         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
5268         char *acct_name;
5269         struct lsa_String lsa_acct_name;
5270         uint32 acb_info;
5271         uint32 acct_flags=0;
5272         uint32 user_rid;
5273         uint32_t access_granted = 0;
5274         union samr_UserInfo info;
5275         unsigned int orig_timeout;
5276
5277         if (argc != 2) {
5278                 d_printf("%s\n%s",
5279                          _("Usage:"),
5280                          _(" net rpc trustdom add <domain_name> "
5281                            "<trust password>\n"));
5282                 return NT_STATUS_INVALID_PARAMETER;
5283         }
5284
5285         /*
5286          * Make valid trusting domain account (ie. uppercased and with '$' appended)
5287          */
5288
5289         if (asprintf(&acct_name, "%s$", argv[0]) < 0) {
5290                 return NT_STATUS_NO_MEMORY;
5291         }
5292
5293         strupper_m(acct_name);
5294
5295         init_lsa_String(&lsa_acct_name, acct_name);
5296
5297         /* Get samr policy handle */
5298         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
5299                                       pipe_hnd->desthost,
5300                                       MAXIMUM_ALLOWED_ACCESS,
5301                                       &connect_pol);
5302         if (!NT_STATUS_IS_OK(result)) {
5303                 goto done;
5304         }
5305
5306         /* Get domain policy handle */
5307         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
5308                                         &connect_pol,
5309                                         MAXIMUM_ALLOWED_ACCESS,
5310                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
5311                                         &domain_pol);
5312         if (!NT_STATUS_IS_OK(result)) {
5313                 goto done;
5314         }
5315
5316         /* This call can take a long time - allow the server to time out.
5317          * 35 seconds should do it. */
5318
5319         orig_timeout = rpccli_set_timeout(pipe_hnd, 35000);
5320
5321         /* Create trusting domain's account */
5322         acb_info = ACB_NORMAL;
5323         acct_flags = SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
5324                      SEC_STD_WRITE_DAC | SEC_STD_DELETE |
5325                      SAMR_USER_ACCESS_SET_PASSWORD |
5326                      SAMR_USER_ACCESS_GET_ATTRIBUTES |
5327                      SAMR_USER_ACCESS_SET_ATTRIBUTES;
5328
5329         result = rpccli_samr_CreateUser2(pipe_hnd, mem_ctx,
5330                                          &domain_pol,
5331                                          &lsa_acct_name,
5332                                          acb_info,
5333                                          acct_flags,
5334                                          &user_pol,
5335                                          &access_granted,
5336                                          &user_rid);
5337
5338         /* And restore our original timeout. */
5339         rpccli_set_timeout(pipe_hnd, orig_timeout);
5340
5341         if (!NT_STATUS_IS_OK(result)) {
5342                 d_printf(_("net rpc trustdom add: create user %s failed %s\n"),
5343                         acct_name, nt_errstr(result));
5344                 goto done;
5345         }
5346
5347         {
5348                 struct samr_CryptPassword crypt_pwd;
5349
5350                 ZERO_STRUCT(info.info23);
5351
5352                 init_samr_CryptPassword(argv[1],
5353                                         &cli->user_session_key,
5354                                         &crypt_pwd);
5355
5356                 info.info23.info.fields_present = SAMR_FIELD_ACCT_FLAGS |
5357                                                   SAMR_FIELD_NT_PASSWORD_PRESENT;
5358                 info.info23.info.acct_flags = ACB_DOMTRUST;
5359                 info.info23.password = crypt_pwd;
5360
5361                 result = rpccli_samr_SetUserInfo2(pipe_hnd, mem_ctx,
5362                                                   &user_pol,
5363                                                   23,
5364                                                   &info);
5365
5366                 if (!NT_STATUS_IS_OK(result)) {
5367                         DEBUG(0,("Could not set trust account password: %s\n",
5368                                  nt_errstr(result)));
5369                         goto done;
5370                 }
5371         }
5372
5373  done:
5374         SAFE_FREE(acct_name);
5375         return result;
5376 }
5377
5378 /**
5379  * Create interdomain trust account for a remote domain.
5380  *
5381  * @param argc Standard argc.
5382  * @param argv Standard argv without initial components.
5383  *
5384  * @return Integer status (0 means success).
5385  **/
5386
5387 static int rpc_trustdom_add(struct net_context *c, int argc, const char **argv)
5388 {
5389         if (argc > 0 && !c->display_usage) {
5390                 return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
5391                                        rpc_trustdom_add_internals, argc, argv);
5392         } else {
5393                 d_printf("%s\n%s",
5394                          _("Usage:"),
5395                          _("net rpc trustdom add <domain_name> <trust "
5396                            "password>\n"));
5397                 return -1;
5398         }
5399 }
5400
5401
5402 /**
5403  * Remove interdomain trust account from the RPC server.
5404  * All parameters (except for argc and argv) are passed by run_rpc_command
5405  * function.
5406  *
5407  * @param c     A net_context structure.
5408  * @param domain_sid The domain sid acquired from the server.
5409  * @param cli A cli_state connected to the server.
5410  * @param mem_ctx Talloc context, destroyed on completion of the function.
5411  * @param argc  Standard main() style argc.
5412  * @param argv  Standard main() style argv. Initial components are already
5413  *              stripped.
5414  *
5415  * @return normal NTSTATUS return code.
5416  */
5417
5418 static NTSTATUS rpc_trustdom_del_internals(struct net_context *c,
5419                                         const DOM_SID *domain_sid,
5420                                         const char *domain_name,
5421                                         struct cli_state *cli,
5422                                         struct rpc_pipe_client *pipe_hnd,
5423                                         TALLOC_CTX *mem_ctx,
5424                                         int argc,
5425                                         const char **argv)
5426 {
5427         struct policy_handle connect_pol, domain_pol, user_pol;
5428         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
5429         char *acct_name;
5430         DOM_SID trust_acct_sid;
5431         struct samr_Ids user_rids, name_types;
5432         struct lsa_String lsa_acct_name;
5433
5434         if (argc != 1) {
5435                 d_printf("%s\n%s",
5436                          _("Usage:"),
5437                          _(" net rpc trustdom del <domain_name>\n"));
5438                 return NT_STATUS_INVALID_PARAMETER;
5439         }
5440
5441         /*
5442          * Make valid trusting domain account (ie. uppercased and with '$' appended)
5443          */
5444         acct_name = talloc_asprintf(mem_ctx, "%s$", argv[0]);
5445
5446         if (acct_name == NULL)
5447                 return NT_STATUS_NO_MEMORY;
5448
5449         strupper_m(acct_name);
5450
5451         /* Get samr policy handle */
5452         result = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
5453                                       pipe_hnd->desthost,
5454                                       MAXIMUM_ALLOWED_ACCESS,
5455                                       &connect_pol);
5456         if (!NT_STATUS_IS_OK(result)) {
5457                 goto done;
5458         }
5459
5460         /* Get domain policy handle */
5461         result = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
5462                                         &connect_pol,
5463                                         MAXIMUM_ALLOWED_ACCESS,
5464                                         CONST_DISCARD(struct dom_sid2 *, domain_sid),
5465                                         &domain_pol);
5466         if (!NT_STATUS_IS_OK(result)) {
5467                 goto done;
5468         }
5469
5470         init_lsa_String(&lsa_acct_name, acct_name);
5471
5472         result = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
5473                                          &domain_pol,
5474                                          1,
5475                                          &lsa_acct_name,
5476                                          &user_rids,
5477                                          &name_types);
5478
5479         if (!NT_STATUS_IS_OK(result)) {
5480                 d_printf(_("net rpc trustdom del: LookupNames on user %s "
5481                            "failed %s\n"),
5482                         acct_name, nt_errstr(result) );
5483                 goto done;
5484         }
5485
5486         result = rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
5487                                       &domain_pol,
5488                                       MAXIMUM_ALLOWED_ACCESS,
5489                                       user_rids.ids[0],
5490                                       &user_pol);
5491
5492         if (!NT_STATUS_IS_OK(result)) {
5493                 d_printf(_("net rpc trustdom del: OpenUser on user %s failed "
5494                            "%s\n"),
5495                         acct_name, nt_errstr(result) );
5496                 goto done;
5497         }
5498
5499         /* append the rid to the domain sid */
5500         if (!sid_compose(&trust_acct_sid, domain_sid, user_rids.ids[0])) {
5501                 goto done;
5502         }
5503
5504         /* remove the sid */
5505
5506         result = rpccli_samr_RemoveMemberFromForeignDomain(pipe_hnd, mem_ctx,
5507                                                            &user_pol,
5508                                                            &trust_acct_sid);
5509         if (!NT_STATUS_IS_OK(result)) {
5510                 d_printf(_("net rpc trustdom del: RemoveMemberFromForeignDomain"
5511                            " on user %s failed %s\n"),
5512                         acct_name, nt_errstr(result) );
5513                 goto done;
5514         }
5515
5516         /* Delete user */
5517
5518         result = rpccli_samr_DeleteUser(pipe_hnd, mem_ctx,
5519                                         &user_pol);
5520
5521         if (!NT_STATUS_IS_OK(result)) {
5522                 d_printf(_("net rpc trustdom del: DeleteUser on user %s failed "
5523                            "%s\n"),
5524                         acct_name, nt_errstr(result) );
5525                 goto done;
5526         }
5527
5528         if (!NT_STATUS_IS_OK(result)) {
5529                 d_printf(_("Could not set trust account password: %s\n"),
5530                    nt_errstr(result));
5531                 goto done;
5532         }
5533
5534  done:
5535         return result;
5536 }
5537
5538 /**
5539  * Delete interdomain trust account for a remote domain.
5540  *
5541  * @param argc Standard argc.
5542  * @param argv Standard argv without initial components.
5543  *
5544  * @return Integer status (0 means success).
5545  **/
5546
5547 static int rpc_trustdom_del(struct net_context *c, int argc, const char **argv)
5548 {
5549         if (argc > 0 && !c->display_usage) {
5550                 return run_rpc_command(c, NULL, &ndr_table_samr.syntax_id, 0,
5551                                        rpc_trustdom_del_internals, argc, argv);
5552         } else {
5553                 d_printf("%s\n%s",
5554                          _("Usage:"),
5555                          _("net rpc trustdom del <domain>\n"));
5556                 return -1;
5557         }
5558 }
5559
5560 static NTSTATUS rpc_trustdom_get_pdc(struct net_context *c,
5561                                      struct cli_state *cli,
5562                                      TALLOC_CTX *mem_ctx,
5563                                      const char *domain_name)
5564 {
5565         char *dc_name = NULL;
5566         const char *buffer = NULL;
5567         struct rpc_pipe_client *netr;
5568         NTSTATUS status;
5569
5570         /* Use NetServerEnum2 */
5571
5572         if (cli_get_pdc_name(cli, domain_name, &dc_name)) {
5573                 SAFE_FREE(dc_name);
5574                 return NT_STATUS_OK;
5575         }
5576
5577         DEBUG(1,("NetServerEnum2 error: Couldn't find primary domain controller\
5578                  for domain %s\n", domain_name));
5579
5580         /* Try netr_GetDcName */
5581
5582         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon.syntax_id,
5583                                           &netr);
5584         if (!NT_STATUS_IS_OK(status)) {
5585                 return status;
5586         }
5587
5588         status = rpccli_netr_GetDcName(netr, mem_ctx,
5589                                        cli->desthost,
5590                                        domain_name,
5591                                        &buffer,
5592                                        NULL);
5593         TALLOC_FREE(netr);
5594
5595         if (NT_STATUS_IS_OK(status)) {
5596                 return status;
5597         }
5598
5599         DEBUG(1,("netr_GetDcName error: Couldn't find primary domain controller\
5600                  for domain %s\n", domain_name));
5601
5602         return status;
5603 }
5604
5605 /**
5606  * Establish trust relationship to a trusting domain.
5607  * Interdomain account must already be created on remote PDC.
5608  *
5609  * @param c    A net_context structure.
5610  * @param argc Standard argc.
5611  * @param argv Standard argv without initial components.
5612  *
5613  * @return Integer status (0 means success).
5614  **/
5615
5616 static int rpc_trustdom_establish(struct net_context *c, int argc,
5617                                   const char **argv)
5618 {
5619         struct cli_state *cli = NULL;
5620         struct sockaddr_storage server_ss;
5621         struct rpc_pipe_client *pipe_hnd = NULL;
5622         struct policy_handle connect_hnd;
5623         TALLOC_CTX *mem_ctx;
5624         NTSTATUS nt_status;
5625         DOM_SID *domain_sid;
5626
5627         char* domain_name;
5628         char* acct_name;
5629         fstring pdc_name;
5630         union lsa_PolicyInformation *info = NULL;
5631
5632         /*
5633          * Connect to \\server\ipc$ as 'our domain' account with password
5634          */
5635
5636         if (argc != 1 || c->display_usage) {
5637                 d_printf("%s\n%s",
5638                          _("Usage:"),
5639                          _("net rpc trustdom establish <domain_name>\n"));
5640                 return -1;
5641         }
5642
5643         domain_name = smb_xstrdup(argv[0]);
5644         strupper_m(domain_name);
5645
5646         /* account name used at first is our domain's name with '$' */
5647         if (asprintf(&acct_name, "%s$", lp_workgroup()) == -1) {
5648                 return -1;
5649         }
5650         strupper_m(acct_name);
5651
5652         /*
5653          * opt_workgroup will be used by connection functions further,
5654          * hence it should be set to remote domain name instead of ours
5655          */
5656         if (c->opt_workgroup) {
5657                 c->opt_workgroup = smb_xstrdup(domain_name);
5658         };
5659
5660         c->opt_user_name = acct_name;
5661
5662         /* find the domain controller */
5663         if (!net_find_pdc(&server_ss, pdc_name, domain_name)) {
5664                 DEBUG(0, ("Couldn't find domain controller for domain %s\n", domain_name));
5665                 return -1;
5666         }
5667
5668         /* connect to ipc$ as username/password */
5669         nt_status = connect_to_ipc(c, &cli, &server_ss, pdc_name);
5670         if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
5671
5672                 /* Is it trusting domain account for sure ? */
5673                 DEBUG(0, ("Couldn't verify trusting domain account. Error was %s\n",
5674                         nt_errstr(nt_status)));
5675                 return -1;
5676         }
5677
5678         /* store who we connected to */
5679
5680         saf_store( domain_name, pdc_name );
5681
5682         /*
5683          * Connect to \\server\ipc$ again (this time anonymously)
5684          */
5685
5686         nt_status = connect_to_ipc_anonymous(c, &cli, &server_ss,
5687                                              (char*)pdc_name);
5688
5689         if (NT_STATUS_IS_ERR(nt_status)) {
5690                 DEBUG(0, ("Couldn't connect to domain %s controller. Error was %s.\n",
5691                         domain_name, nt_errstr(nt_status)));
5692                 return -1;
5693         }
5694
5695         if (!(mem_ctx = talloc_init("establishing trust relationship to "
5696                                     "domain %s", domain_name))) {
5697                 DEBUG(0, ("talloc_init() failed\n"));
5698                 cli_shutdown(cli);
5699                 return -1;
5700         }
5701
5702         /* Make sure we're talking to a proper server */
5703
5704         nt_status = rpc_trustdom_get_pdc(c, cli, mem_ctx, domain_name);
5705         if (!NT_STATUS_IS_OK(nt_status)) {
5706                 cli_shutdown(cli);
5707                 talloc_destroy(mem_ctx);
5708                 return -1;
5709         }
5710
5711         /*
5712          * Call LsaOpenPolicy and LsaQueryInfo
5713          */
5714
5715         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
5716                                              &pipe_hnd);
5717         if (!NT_STATUS_IS_OK(nt_status)) {
5718                 DEBUG(0, ("Could not initialise lsa pipe. Error was %s\n", nt_errstr(nt_status) ));
5719                 cli_shutdown(cli);
5720                 talloc_destroy(mem_ctx);
5721                 return -1;
5722         }
5723
5724         nt_status = rpccli_lsa_open_policy2(pipe_hnd, mem_ctx, true, KEY_QUERY_VALUE,
5725                                          &connect_hnd);
5726         if (NT_STATUS_IS_ERR(nt_status)) {
5727                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
5728                         nt_errstr(nt_status)));
5729                 cli_shutdown(cli);
5730                 talloc_destroy(mem_ctx);
5731                 return -1;
5732         }
5733
5734         /* Querying info level 5 */
5735
5736         nt_status = rpccli_lsa_QueryInfoPolicy(pipe_hnd, mem_ctx,
5737                                                &connect_hnd,
5738                                                LSA_POLICY_INFO_ACCOUNT_DOMAIN,
5739                                                &info);
5740         if (NT_STATUS_IS_ERR(nt_status)) {
5741                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
5742                         nt_errstr(nt_status)));
5743                 cli_shutdown(cli);
5744                 talloc_destroy(mem_ctx);
5745                 return -1;
5746         }
5747
5748         domain_sid = info->account_domain.sid;
5749
5750         /* There should be actually query info level 3 (following nt serv behaviour),
5751            but I still don't know if it's _really_ necessary */
5752
5753         /*
5754          * Store the password in secrets db
5755          */
5756
5757         if (!pdb_set_trusteddom_pw(domain_name, c->opt_password, domain_sid)) {
5758                 DEBUG(0, ("Storing password for trusted domain failed.\n"));
5759                 cli_shutdown(cli);
5760                 talloc_destroy(mem_ctx);
5761                 return -1;
5762         }
5763
5764         /*
5765          * Close the pipes and clean up
5766          */
5767
5768         nt_status = rpccli_lsa_Close(pipe_hnd, mem_ctx, &connect_hnd);
5769         if (NT_STATUS_IS_ERR(nt_status)) {
5770                 DEBUG(0, ("Couldn't close LSA pipe. Error was %s\n",
5771                         nt_errstr(nt_status)));
5772                 cli_shutdown(cli);
5773                 talloc_destroy(mem_ctx);
5774                 return -1;
5775         }
5776
5777         cli_shutdown(cli);
5778
5779         talloc_destroy(mem_ctx);
5780
5781         d_printf(_("Trust to domain %s established\n"), domain_name);
5782         return 0;
5783 }
5784
5785 /**
5786  * Revoke trust relationship to the remote domain.
5787  *
5788  * @param c    A net_context structure.
5789  * @param argc Standard argc.
5790  * @param argv Standard argv without initial components.
5791  *
5792  * @return Integer status (0 means success).
5793  **/
5794
5795 static int rpc_trustdom_revoke(struct net_context *c, int argc,
5796                                const char **argv)
5797 {
5798         char* domain_name;
5799         int rc = -1;
5800
5801         if (argc < 1 || c->display_usage) {
5802                 d_printf("%s\n%s",
5803                          _("Usage:"),
5804                          _("net rpc trustdom revoke <domain_name>\n"
5805                            "  Revoke trust relationship\n"
5806                            "    domain_name\tName of domain to revoke trust\n"));
5807                 return -1;
5808         }
5809
5810         /* generate upper cased domain name */
5811         domain_name = smb_xstrdup(argv[0]);
5812         strupper_m(domain_name);
5813
5814         /* delete password of the trust */
5815         if (!pdb_del_trusteddom_pw(domain_name)) {
5816                 DEBUG(0, ("Failed to revoke relationship to the trusted domain %s\n",
5817                           domain_name));
5818                 goto done;
5819         };
5820
5821         rc = 0;
5822 done:
5823         SAFE_FREE(domain_name);
5824         return rc;
5825 }
5826
5827 static NTSTATUS rpc_query_domain_sid(struct net_context *c,
5828                                         const DOM_SID *domain_sid,
5829                                         const char *domain_name,
5830                                         struct cli_state *cli,
5831                                         struct rpc_pipe_client *pipe_hnd,
5832                                         TALLOC_CTX *mem_ctx,
5833                                         int argc,
5834                                         const char **argv)
5835 {
5836         fstring str_sid;
5837         if (!sid_to_fstring(str_sid, domain_sid)) {
5838                 return NT_STATUS_UNSUCCESSFUL;
5839         }
5840         d_printf("%s\n", str_sid);
5841         return NT_STATUS_OK;
5842 }
5843
5844 static void print_trusted_domain(DOM_SID *dom_sid, const char *trusted_dom_name)
5845 {
5846         fstring ascii_sid;
5847
5848         /* convert sid into ascii string */
5849         sid_to_fstring(ascii_sid, dom_sid);
5850
5851         d_printf("%-20s%s\n", trusted_dom_name, ascii_sid);
5852 }
5853
5854 static NTSTATUS vampire_trusted_domain(struct rpc_pipe_client *pipe_hnd,
5855                                       TALLOC_CTX *mem_ctx,
5856                                       struct policy_handle *pol,
5857                                       DOM_SID dom_sid,
5858                                       const char *trusted_dom_name)
5859 {
5860         NTSTATUS nt_status;
5861         union lsa_TrustedDomainInfo *info = NULL;
5862         char *cleartextpwd = NULL;
5863         uint8_t session_key[16];
5864         DATA_BLOB session_key_blob;
5865         DATA_BLOB data = data_blob_null;
5866
5867         nt_status = rpccli_lsa_QueryTrustedDomainInfoBySid(pipe_hnd, mem_ctx,
5868                                                            pol,
5869                                                            &dom_sid,
5870                                                            LSA_TRUSTED_DOMAIN_INFO_PASSWORD,
5871                                                            &info);
5872         if (NT_STATUS_IS_ERR(nt_status)) {
5873                 DEBUG(0,("Could not query trusted domain info. Error was %s\n",
5874                 nt_errstr(nt_status)));
5875                 goto done;
5876         }
5877
5878         data = data_blob(info->password.password->data,
5879                          info->password.password->length);
5880
5881         if (!rpccli_get_pwd_hash(pipe_hnd, session_key)) {
5882                 DEBUG(0, ("Could not retrieve password hash\n"));
5883                 goto done;
5884         }
5885
5886         session_key_blob = data_blob_const(session_key, sizeof(session_key));
5887         cleartextpwd = sess_decrypt_string(mem_ctx, &data, &session_key_blob);
5888
5889         if (cleartextpwd == NULL) {
5890                 DEBUG(0,("retrieved NULL password\n"));
5891                 nt_status = NT_STATUS_UNSUCCESSFUL;
5892                 goto done;
5893         }
5894
5895         if (!pdb_set_trusteddom_pw(trusted_dom_name, cleartextpwd, &dom_sid)) {
5896                 DEBUG(0, ("Storing password for trusted domain failed.\n"));
5897                 nt_status = NT_STATUS_UNSUCCESSFUL;
5898                 goto done;
5899         }
5900
5901 #ifdef DEBUG_PASSWORD
5902         DEBUG(100,("successfully vampired trusted domain [%s], sid: [%s], "
5903                    "password: [%s]\n", trusted_dom_name,
5904                    sid_string_dbg(&dom_sid), cleartextpwd));
5905 #endif
5906
5907 done:
5908         SAFE_FREE(cleartextpwd);
5909         data_blob_free(&data);
5910
5911         return nt_status;
5912 }
5913
5914 static int rpc_trustdom_vampire(struct net_context *c, int argc,
5915                                 const char **argv)
5916 {
5917         /* common variables */
5918         TALLOC_CTX* mem_ctx;
5919         struct cli_state *cli = NULL;
5920         struct rpc_pipe_client *pipe_hnd = NULL;
5921         NTSTATUS nt_status;
5922         const char *domain_name = NULL;
5923         DOM_SID *queried_dom_sid;
5924         struct policy_handle connect_hnd;
5925         union lsa_PolicyInformation *info = NULL;
5926
5927         /* trusted domains listing variables */
5928         unsigned int enum_ctx = 0;
5929         int i;
5930         struct lsa_DomainList dom_list;
5931         fstring pdc_name;
5932
5933         if (c->display_usage) {
5934                 d_printf(  "%s\n"
5935                            "net rpc trustdom vampire\n"
5936                            "  %s\n",
5937                          _("Usage:"),
5938                          _("Vampire trust relationship from remote server"));
5939                 return 0;
5940         }
5941
5942         /*
5943          * Listing trusted domains (stored in secrets.tdb, if local)
5944          */
5945
5946         mem_ctx = talloc_init("trust relationships vampire");
5947
5948         /*
5949          * set domain and pdc name to local samba server (default)
5950          * or to remote one given in command line
5951          */
5952
5953         if (StrCaseCmp(c->opt_workgroup, lp_workgroup())) {
5954                 domain_name = c->opt_workgroup;
5955                 c->opt_target_workgroup = c->opt_workgroup;
5956         } else {
5957                 fstrcpy(pdc_name, global_myname());
5958                 domain_name = talloc_strdup(mem_ctx, lp_workgroup());
5959                 c->opt_target_workgroup = domain_name;
5960         };
5961
5962         /* open \PIPE\lsarpc and open policy handle */
5963         nt_status = net_make_ipc_connection(c, NET_FLAGS_PDC, &cli);
5964         if (!NT_STATUS_IS_OK(nt_status)) {
5965                 DEBUG(0, ("Couldn't connect to domain controller: %s\n",
5966                           nt_errstr(nt_status)));
5967                 talloc_destroy(mem_ctx);
5968                 return -1;
5969         };
5970
5971         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
5972                                              &pipe_hnd);
5973         if (!NT_STATUS_IS_OK(nt_status)) {
5974                 DEBUG(0, ("Could not initialise lsa pipe. Error was %s\n",
5975                         nt_errstr(nt_status) ));
5976                 cli_shutdown(cli);
5977                 talloc_destroy(mem_ctx);
5978                 return -1;
5979         };
5980
5981         nt_status = rpccli_lsa_open_policy2(pipe_hnd, mem_ctx, false, KEY_QUERY_VALUE,
5982                                         &connect_hnd);
5983         if (NT_STATUS_IS_ERR(nt_status)) {
5984                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
5985                         nt_errstr(nt_status)));
5986                 cli_shutdown(cli);
5987                 talloc_destroy(mem_ctx);
5988                 return -1;
5989         };
5990
5991         /* query info level 5 to obtain sid of a domain being queried */
5992         nt_status = rpccli_lsa_QueryInfoPolicy(pipe_hnd, mem_ctx,
5993                                                &connect_hnd,
5994                                                LSA_POLICY_INFO_ACCOUNT_DOMAIN,
5995                                                &info);
5996
5997         if (NT_STATUS_IS_ERR(nt_status)) {
5998                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
5999                         nt_errstr(nt_status)));
6000                 cli_shutdown(cli);
6001                 talloc_destroy(mem_ctx);
6002                 return -1;
6003         }
6004
6005         queried_dom_sid = info->account_domain.sid;
6006
6007         /*
6008          * Keep calling LsaEnumTrustdom over opened pipe until
6009          * the end of enumeration is reached
6010          */
6011
6012         d_printf(_("Vampire trusted domains:\n\n"));
6013
6014         do {
6015                 nt_status = rpccli_lsa_EnumTrustDom(pipe_hnd, mem_ctx,
6016                                                     &connect_hnd,
6017                                                     &enum_ctx,
6018                                                     &dom_list,
6019                                                     (uint32_t)-1);
6020                 if (NT_STATUS_IS_ERR(nt_status)) {
6021                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
6022                                 nt_errstr(nt_status)));
6023                         cli_shutdown(cli);
6024                         talloc_destroy(mem_ctx);
6025                         return -1;
6026                 };
6027
6028                 for (i = 0; i < dom_list.count; i++) {
6029
6030                         print_trusted_domain(dom_list.domains[i].sid,
6031                                              dom_list.domains[i].name.string);
6032
6033                         nt_status = vampire_trusted_domain(pipe_hnd, mem_ctx, &connect_hnd, 
6034                                                            *dom_list.domains[i].sid,
6035                                                            dom_list.domains[i].name.string);
6036                         if (!NT_STATUS_IS_OK(nt_status)) {
6037                                 cli_shutdown(cli);
6038                                 talloc_destroy(mem_ctx);
6039                                 return -1;
6040                         }
6041                 };
6042
6043                 /*
6044                  * in case of no trusted domains say something rather
6045                  * than just display blank line
6046                  */
6047                 if (!dom_list.count) d_printf(_("none\n"));
6048
6049         } while (NT_STATUS_EQUAL(nt_status, STATUS_MORE_ENTRIES));
6050
6051         /* close this connection before doing next one */
6052         nt_status = rpccli_lsa_Close(pipe_hnd, mem_ctx, &connect_hnd);
6053         if (NT_STATUS_IS_ERR(nt_status)) {
6054                 DEBUG(0, ("Couldn't properly close lsa policy handle. Error was %s\n",
6055                         nt_errstr(nt_status)));
6056                 cli_shutdown(cli);
6057                 talloc_destroy(mem_ctx);
6058                 return -1;
6059         };
6060
6061         /* close lsarpc pipe and connection to IPC$ */
6062         cli_shutdown(cli);
6063
6064         talloc_destroy(mem_ctx);
6065         return 0;
6066 }
6067
6068 static int rpc_trustdom_list(struct net_context *c, int argc, const char **argv)
6069 {
6070         /* common variables */
6071         TALLOC_CTX* mem_ctx;
6072         struct cli_state *cli = NULL, *remote_cli = NULL;
6073         struct rpc_pipe_client *pipe_hnd = NULL;
6074         NTSTATUS nt_status;
6075         const char *domain_name = NULL;
6076         DOM_SID *queried_dom_sid;
6077         int ascii_dom_name_len;
6078         struct policy_handle connect_hnd;
6079         union lsa_PolicyInformation *info = NULL;
6080
6081         /* trusted domains listing variables */
6082         unsigned int num_domains, enum_ctx = 0;
6083         int i;
6084         struct lsa_DomainList dom_list;
6085         fstring pdc_name;
6086         bool found_domain;
6087
6088         /* trusting domains listing variables */
6089         struct policy_handle domain_hnd;
6090         struct samr_SamArray *trusts = NULL;
6091
6092         if (c->display_usage) {
6093                 d_printf(  "%s\n"
6094                            "net rpc trustdom list\n"
6095                            "    %s\n",
6096                          _("Usage:"),
6097                          _("List incoming and outgoing trust relationships"));
6098                 return 0;
6099         }
6100
6101         /*
6102          * Listing trusted domains (stored in secrets.tdb, if local)
6103          */
6104
6105         mem_ctx = talloc_init("trust relationships listing");
6106
6107         /*
6108          * set domain and pdc name to local samba server (default)
6109          * or to remote one given in command line
6110          */
6111
6112         if (StrCaseCmp(c->opt_workgroup, lp_workgroup())) {
6113                 domain_name = c->opt_workgroup;
6114                 c->opt_target_workgroup = c->opt_workgroup;
6115         } else {
6116                 fstrcpy(pdc_name, global_myname());
6117                 domain_name = talloc_strdup(mem_ctx, lp_workgroup());
6118                 c->opt_target_workgroup = domain_name;
6119         };
6120
6121         /* open \PIPE\lsarpc and open policy handle */
6122         nt_status = net_make_ipc_connection(c, NET_FLAGS_PDC, &cli);
6123         if (!NT_STATUS_IS_OK(nt_status)) {
6124                 DEBUG(0, ("Couldn't connect to domain controller: %s\n",
6125                           nt_errstr(nt_status)));
6126                 talloc_destroy(mem_ctx);
6127                 return -1;
6128         };
6129
6130         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
6131                                              &pipe_hnd);
6132         if (!NT_STATUS_IS_OK(nt_status)) {
6133                 DEBUG(0, ("Could not initialise lsa pipe. Error was %s\n",
6134                         nt_errstr(nt_status) ));
6135                 cli_shutdown(cli);
6136                 talloc_destroy(mem_ctx);
6137                 return -1;
6138         };
6139
6140         nt_status = rpccli_lsa_open_policy2(pipe_hnd, mem_ctx, false, KEY_QUERY_VALUE,
6141                                         &connect_hnd);
6142         if (NT_STATUS_IS_ERR(nt_status)) {
6143                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
6144                         nt_errstr(nt_status)));
6145                 cli_shutdown(cli);
6146                 talloc_destroy(mem_ctx);
6147                 return -1;
6148         };
6149         
6150         /* query info level 5 to obtain sid of a domain being queried */
6151         nt_status = rpccli_lsa_QueryInfoPolicy(pipe_hnd, mem_ctx,
6152                                                &connect_hnd,
6153                                                LSA_POLICY_INFO_ACCOUNT_DOMAIN,
6154                                                &info);
6155
6156         if (NT_STATUS_IS_ERR(nt_status)) {
6157                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
6158                         nt_errstr(nt_status)));
6159                 cli_shutdown(cli);
6160                 talloc_destroy(mem_ctx);
6161                 return -1;
6162         }
6163
6164         queried_dom_sid = info->account_domain.sid;
6165
6166         /*
6167          * Keep calling LsaEnumTrustdom over opened pipe until
6168          * the end of enumeration is reached
6169          */
6170
6171         d_printf(_("Trusted domains list:\n\n"));
6172
6173         found_domain = false;
6174
6175         do {
6176                 nt_status = rpccli_lsa_EnumTrustDom(pipe_hnd, mem_ctx,
6177                                                     &connect_hnd,
6178                                                     &enum_ctx,
6179                                                     &dom_list,
6180                                                     (uint32_t)-1);
6181                 if (NT_STATUS_IS_ERR(nt_status)) {
6182                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
6183                                 nt_errstr(nt_status)));
6184                         cli_shutdown(cli);
6185                         talloc_destroy(mem_ctx);
6186                         return -1;
6187                 };
6188
6189                 for (i = 0; i < dom_list.count; i++) {
6190                         print_trusted_domain(dom_list.domains[i].sid,
6191                                              dom_list.domains[i].name.string);
6192                         found_domain = true;
6193                 };
6194
6195
6196         } while (NT_STATUS_EQUAL(nt_status, STATUS_MORE_ENTRIES));
6197
6198         /*
6199          * in case of no trusted domains say something rather
6200          * than just display blank line
6201          */
6202         if (!found_domain) {
6203                 d_printf(_("none\n"));
6204         }
6205
6206         /* close this connection before doing next one */
6207         nt_status = rpccli_lsa_Close(pipe_hnd, mem_ctx, &connect_hnd);
6208         if (NT_STATUS_IS_ERR(nt_status)) {
6209                 DEBUG(0, ("Couldn't properly close lsa policy handle. Error was %s\n",
6210                         nt_errstr(nt_status)));
6211                 cli_shutdown(cli);
6212                 talloc_destroy(mem_ctx);
6213                 return -1;
6214         };
6215         
6216         TALLOC_FREE(pipe_hnd);
6217
6218         /*
6219          * Listing trusting domains (stored in passdb backend, if local)
6220          */
6221         
6222         d_printf(_("\nTrusting domains list:\n\n"));
6223
6224         /*
6225          * Open \PIPE\samr and get needed policy handles
6226          */
6227         nt_status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr.syntax_id,
6228                                              &pipe_hnd);
6229         if (!NT_STATUS_IS_OK(nt_status)) {
6230                 DEBUG(0, ("Could not initialise samr pipe. Error was %s\n", nt_errstr(nt_status)));
6231                 cli_shutdown(cli);
6232                 talloc_destroy(mem_ctx);
6233                 return -1;
6234         };
6235
6236         /* SamrConnect2 */
6237         nt_status = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
6238                                          pipe_hnd->desthost,
6239                                          SAMR_ACCESS_LOOKUP_DOMAIN,
6240                                          &connect_hnd);
6241         if (!NT_STATUS_IS_OK(nt_status)) {
6242                 DEBUG(0, ("Couldn't open SAMR policy handle. Error was %s\n",
6243                         nt_errstr(nt_status)));
6244                 cli_shutdown(cli);
6245                 talloc_destroy(mem_ctx);
6246                 return -1;
6247         };
6248
6249         /* SamrOpenDomain - we have to open domain policy handle in order to be
6250            able to enumerate accounts*/
6251         nt_status = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
6252                                            &connect_hnd,
6253                                            SAMR_DOMAIN_ACCESS_ENUM_ACCOUNTS,
6254                                            queried_dom_sid,
6255                                            &domain_hnd);
6256         if (!NT_STATUS_IS_OK(nt_status)) {
6257                 DEBUG(0, ("Couldn't open domain object. Error was %s\n",
6258                         nt_errstr(nt_status)));
6259                 cli_shutdown(cli);
6260                 talloc_destroy(mem_ctx);
6261                 return -1;
6262         };
6263
6264         /*
6265          * perform actual enumeration
6266          */
6267
6268         found_domain = false;
6269
6270         enum_ctx = 0;   /* reset enumeration context from last enumeration */
6271         do {
6272
6273                 nt_status = rpccli_samr_EnumDomainUsers(pipe_hnd, mem_ctx,
6274                                                         &domain_hnd,
6275                                                         &enum_ctx,
6276                                                         ACB_DOMTRUST,
6277                                                         &trusts,
6278                                                         0xffff,
6279                                                         &num_domains);
6280                 if (NT_STATUS_IS_ERR(nt_status)) {
6281                         DEBUG(0, ("Couldn't enumerate accounts. Error was: %s\n",
6282                                 nt_errstr(nt_status)));
6283                         cli_shutdown(cli);
6284                         talloc_destroy(mem_ctx);
6285                         return -1;
6286                 };
6287
6288                 for (i = 0; i < num_domains; i++) {
6289
6290                         char *str = CONST_DISCARD(char *, trusts->entries[i].name.string);
6291
6292                         found_domain = true;
6293
6294                         /*
6295                          * get each single domain's sid (do we _really_ need this ?):
6296                          *  1) connect to domain's pdc
6297                          *  2) query the pdc for domain's sid
6298                          */
6299
6300                         /* get rid of '$' tail */
6301                         ascii_dom_name_len = strlen(str);
6302                         if (ascii_dom_name_len && ascii_dom_name_len < FSTRING_LEN)
6303                                 str[ascii_dom_name_len - 1] = '\0';
6304
6305                         /* set opt_* variables to remote domain */
6306                         strupper_m(str);
6307                         c->opt_workgroup = talloc_strdup(mem_ctx, str);
6308                         c->opt_target_workgroup = c->opt_workgroup;
6309
6310                         d_printf("%-20s", str);
6311
6312                         /* connect to remote domain controller */
6313                         nt_status = net_make_ipc_connection(c,
6314                                         NET_FLAGS_PDC | NET_FLAGS_ANONYMOUS,
6315                                         &remote_cli);
6316                         if (NT_STATUS_IS_OK(nt_status)) {
6317                                 /* query for domain's sid */
6318                                 if (run_rpc_command(
6319                                             c, remote_cli,
6320                                             &ndr_table_lsarpc.syntax_id, 0,
6321                                             rpc_query_domain_sid, argc,
6322                                             argv))
6323                                         d_printf(_("strange - couldn't get domain's sid\n"));
6324
6325                                 cli_shutdown(remote_cli);
6326
6327                         } else {
6328                                 d_fprintf(stderr, _("domain controller is not "
6329                                           "responding: %s\n"),
6330                                           nt_errstr(nt_status));
6331                                 d_printf(_("couldn't get domain's sid\n"));
6332                         }
6333                 }
6334
6335         } while (NT_STATUS_EQUAL(nt_status, STATUS_MORE_ENTRIES));
6336
6337         if (!found_domain) {
6338                 d_printf("none\n");
6339         }
6340
6341         /* close opened samr and domain policy handles */
6342         nt_status = rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_hnd);
6343         if (!NT_STATUS_IS_OK(nt_status)) {
6344                 DEBUG(0, ("Couldn't properly close domain policy handle for domain %s\n", domain_name));
6345         };
6346
6347         nt_status = rpccli_samr_Close(pipe_hnd, mem_ctx, &connect_hnd);
6348         if (!NT_STATUS_IS_OK(nt_status)) {
6349                 DEBUG(0, ("Couldn't properly close samr policy handle for domain %s\n", domain_name));
6350         };
6351
6352         /* close samr pipe and connection to IPC$ */
6353         cli_shutdown(cli);
6354
6355         talloc_destroy(mem_ctx);
6356         return 0;
6357 }
6358
6359 /**
6360  * Entrypoint for 'net rpc trustdom' code.
6361  *
6362  * @param argc Standard argc.
6363  * @param argv Standard argv without initial components.
6364  *
6365  * @return Integer status (0 means success).
6366  */
6367
6368 static int rpc_trustdom(struct net_context *c, int argc, const char **argv)
6369 {
6370         struct functable func[] = {
6371                 {
6372                         "add",
6373                         rpc_trustdom_add,
6374                         NET_TRANSPORT_RPC,
6375                         N_("Add trusting domain's account"),
6376                         N_("net rpc trustdom add\n"
6377                            "    Add trusting domain's account")
6378                 },
6379                 {
6380                         "del",
6381                         rpc_trustdom_del,
6382                         NET_TRANSPORT_RPC,
6383                         N_("Remove trusting domain's account"),
6384                         N_("net rpc trustdom del\n"
6385                            "    Remove trusting domain's account")
6386                 },
6387                 {
6388                         "establish",
6389                         rpc_trustdom_establish,
6390                         NET_TRANSPORT_RPC,
6391                         N_("Establish outgoing trust relationship"),
6392                         N_("net rpc trustdom establish\n"
6393                            "    Establish outgoing trust relationship")
6394                 },
6395                 {
6396                         "revoke",
6397                         rpc_trustdom_revoke,
6398                         NET_TRANSPORT_RPC,
6399                         N_("Revoke outgoing trust relationship"),
6400                         N_("net rpc trustdom revoke\n"
6401                            "    Revoke outgoing trust relationship")
6402                 },
6403                 {
6404                         "list",
6405                         rpc_trustdom_list,
6406                         NET_TRANSPORT_RPC,
6407                         N_("List in- and outgoing domain trusts"),
6408                         N_("net rpc trustdom list\n"
6409                            "    List in- and outgoing domain trusts")
6410                 },
6411                 {
6412                         "vampire",
6413                         rpc_trustdom_vampire,
6414                         NET_TRANSPORT_RPC,
6415                         N_("Vampire trusts from remote server"),
6416                         N_("net rpc trustdom vampire\n"
6417                            "    Vampire trusts from remote server")
6418                 },
6419                 {NULL, NULL, 0, NULL, NULL}
6420         };
6421
6422         return net_run_function(c, argc, argv, "net rpc trustdom", func);
6423 }
6424
6425 /**
6426  * Check if a server will take rpc commands
6427  * @param flags Type of server to connect to (PDC, DMB, localhost)
6428  *              if the host is not explicitly specified
6429  * @return  bool (true means rpc supported)
6430  */
6431 bool net_rpc_check(struct net_context *c, unsigned flags)
6432 {
6433         struct cli_state *cli;
6434         bool ret = false;
6435         struct sockaddr_storage server_ss;
6436         char *server_name = NULL;
6437         NTSTATUS status;
6438
6439         /* flags (i.e. server type) may depend on command */
6440         if (!net_find_server(c, NULL, flags, &server_ss, &server_name))
6441                 return false;
6442
6443         if ((cli = cli_initialise()) == NULL) {
6444                 return false;
6445         }
6446
6447         status = cli_connect(cli, server_name, &server_ss);
6448         if (!NT_STATUS_IS_OK(status))
6449                 goto done;
6450         if (!attempt_netbios_session_request(&cli, global_myname(),
6451                                              server_name, &server_ss))
6452                 goto done;
6453         status = cli_negprot(cli);
6454         if (!NT_STATUS_IS_OK(status))
6455                 goto done;
6456         if (cli->protocol < PROTOCOL_NT1)
6457                 goto done;
6458
6459         ret = true;
6460  done:
6461         cli_shutdown(cli);
6462         return ret;
6463 }
6464
6465 /* dump sam database via samsync rpc calls */
6466 static int rpc_samdump(struct net_context *c, int argc, const char **argv) {
6467         if (c->display_usage) {
6468                 d_printf(  "%s\n"
6469                            "net rpc samdump\n"
6470                            "    %s\n",
6471                          _("Usage:"),
6472                          _("Dump remote SAM database"));
6473                 return 0;
6474         }
6475
6476         return run_rpc_command(c, NULL, &ndr_table_netlogon.syntax_id,
6477                                NET_FLAGS_ANONYMOUS,
6478                                rpc_samdump_internals, argc, argv);
6479 }
6480
6481 /* syncronise sam database via samsync rpc calls */
6482 static int rpc_vampire(struct net_context *c, int argc, const char **argv)
6483 {
6484         struct functable func[] = {
6485                 {
6486                         "ldif",
6487                         rpc_vampire_ldif,
6488                         NET_TRANSPORT_RPC,
6489                         N_("Dump remote SAM database to ldif"),
6490                         N_("net rpc vampire ldif\n"
6491                            "    Dump remote SAM database to LDIF file or "
6492                            "stdout")
6493                 },
6494                 {
6495                         "keytab",
6496                         rpc_vampire_keytab,
6497                         NET_TRANSPORT_RPC,
6498                         N_("Dump remote SAM database to Kerberos Keytab"),
6499                         N_("net rpc vampire keytab\n"
6500                            "    Dump remote SAM database to Kerberos keytab "
6501                            "file")
6502                 },
6503                 {
6504                         "passdb",
6505                         rpc_vampire_passdb,
6506                         NET_TRANSPORT_RPC,
6507                         N_("Dump remote SAM database to passdb"),
6508                         N_("net rpc vampire passdb\n"
6509                            "    Dump remote SAM database to passdb")
6510                 },
6511
6512                 {NULL, NULL, 0, NULL, NULL}
6513         };
6514
6515         if (argc == 0) {
6516                 if (c->display_usage) {
6517                         d_printf(  "%s\n"
6518                                    "net rpc vampire\n"
6519                                    "    %s\n",
6520                                  _("Usage:"),
6521                                  _("Vampire remote SAM database"));
6522                         return 0;
6523                 }
6524
6525                 return run_rpc_command(c, NULL, &ndr_table_netlogon.syntax_id,
6526                                        NET_FLAGS_ANONYMOUS,
6527                                        rpc_vampire_internals,
6528                                        argc, argv);
6529         }
6530
6531         return net_run_function(c, argc, argv, "net rpc vampire", func);
6532 }
6533
6534 /**
6535  * Migrate everything from a print server.
6536  *
6537  * @param c     A net_context structure.
6538  * @param argc  Standard main() style argc.
6539  * @param argv  Standard main() style argv. Initial components are already
6540  *              stripped.
6541  *
6542  * @return A shell status integer (0 for success).
6543  *
6544  * The order is important !
6545  * To successfully add drivers the print queues have to exist !
6546  * Applying ACLs should be the last step, because you're easily locked out.
6547  *
6548  **/
6549 static int rpc_printer_migrate_all(struct net_context *c, int argc,
6550                                    const char **argv)
6551 {
6552         int ret;
6553
6554         if (c->display_usage) {
6555                 d_printf(  "%s\n"
6556                            "net rpc printer migrate all\n"
6557                            "    %s\n",
6558                          _("Usage:"),
6559                          _("Migrate everything from a print server"));
6560                 return 0;
6561         }
6562
6563         if (!c->opt_host) {
6564                 d_printf(_("no server to migrate\n"));
6565                 return -1;
6566         }
6567
6568         ret = run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6569                               rpc_printer_migrate_printers_internals, argc,
6570                               argv);
6571         if (ret)
6572                 return ret;
6573
6574         ret = run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6575                               rpc_printer_migrate_drivers_internals, argc,
6576                               argv);
6577         if (ret)
6578                 return ret;
6579
6580         ret = run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6581                               rpc_printer_migrate_forms_internals, argc, argv);
6582         if (ret)
6583                 return ret;
6584
6585         ret = run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6586                               rpc_printer_migrate_settings_internals, argc,
6587                               argv);
6588         if (ret)
6589                 return ret;
6590
6591         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6592                                rpc_printer_migrate_security_internals, argc,
6593                                argv);
6594
6595 }
6596
6597 /**
6598  * Migrate print drivers from a print server.
6599  *
6600  * @param c     A net_context structure.
6601  * @param argc  Standard main() style argc.
6602  * @param argv  Standard main() style argv. Initial components are already
6603  *              stripped.
6604  *
6605  * @return A shell status integer (0 for success).
6606  **/
6607 static int rpc_printer_migrate_drivers(struct net_context *c, int argc,
6608                                        const char **argv)
6609 {
6610         if (c->display_usage) {
6611                 d_printf(  "%s\n"
6612                            "net rpc printer migrate drivers\n"
6613                            "     %s\n",
6614                          _("Usage:"),
6615                          _("Migrate print-drivers from a print-server"));
6616                 return 0;
6617         }
6618
6619         if (!c->opt_host) {
6620                 d_printf(_("no server to migrate\n"));
6621                 return -1;
6622         }
6623
6624         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6625                                rpc_printer_migrate_drivers_internals,
6626                                argc, argv);
6627 }
6628
6629 /**
6630  * Migrate print-forms from a print-server.
6631  *
6632  * @param c     A net_context structure.
6633  * @param argc  Standard main() style argc.
6634  * @param argv  Standard main() style argv. Initial components are already
6635  *              stripped.
6636  *
6637  * @return A shell status integer (0 for success).
6638  **/
6639 static int rpc_printer_migrate_forms(struct net_context *c, int argc,
6640                                      const char **argv)
6641 {
6642         if (c->display_usage) {
6643                 d_printf(  "%s\n"
6644                            "net rpc printer migrate forms\n"
6645                            "    %s\n",
6646                          _("Usage:"),
6647                          _("Migrate print-forms from a print-server"));
6648                 return 0;
6649         }
6650
6651         if (!c->opt_host) {
6652                 d_printf(_("no server to migrate\n"));
6653                 return -1;
6654         }
6655
6656         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6657                                rpc_printer_migrate_forms_internals,
6658                                argc, argv);
6659 }
6660
6661 /**
6662  * Migrate printers from a print-server.
6663  *
6664  * @param c     A net_context structure.
6665  * @param argc  Standard main() style argc.
6666  * @param argv  Standard main() style argv. Initial components are already
6667  *              stripped.
6668  *
6669  * @return A shell status integer (0 for success).
6670  **/
6671 static int rpc_printer_migrate_printers(struct net_context *c, int argc,
6672                                         const char **argv)
6673 {
6674         if (c->display_usage) {
6675                 d_printf(  "%s\n"
6676                            "net rpc printer migrate printers\n"
6677                            "    %s\n",
6678                          _("Usage:"),
6679                          _("Migrate printers from a print-server"));
6680                 return 0;
6681         }
6682
6683         if (!c->opt_host) {
6684                 d_printf(_("no server to migrate\n"));
6685                 return -1;
6686         }
6687
6688         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6689                                rpc_printer_migrate_printers_internals,
6690                                argc, argv);
6691 }
6692
6693 /**
6694  * Migrate printer-ACLs from a print-server
6695  *
6696  * @param c     A net_context structure.
6697  * @param argc  Standard main() style argc.
6698  * @param argv  Standard main() style argv. Initial components are already
6699  *              stripped.
6700  *
6701  * @return A shell status integer (0 for success).
6702  **/
6703 static int rpc_printer_migrate_security(struct net_context *c, int argc,
6704                                         const char **argv)
6705 {
6706         if (c->display_usage) {
6707                 d_printf(  "%s\n"
6708                            "net rpc printer migrate security\n"
6709                            "    %s\n",
6710                          _("Usage:"),
6711                          _("Migrate printer-ACLs from a print-server"));
6712                 return 0;
6713         }
6714
6715         if (!c->opt_host) {
6716                 d_printf(_("no server to migrate\n"));
6717                 return -1;
6718         }
6719
6720         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6721                                rpc_printer_migrate_security_internals,
6722                                argc, argv);
6723 }
6724
6725 /**
6726  * Migrate printer-settings from a print-server.
6727  *
6728  * @param c     A net_context structure.
6729  * @param argc  Standard main() style argc.
6730  * @param argv  Standard main() style argv. Initial components are already
6731  *              stripped.
6732  *
6733  * @return A shell status integer (0 for success).
6734  **/
6735 static int rpc_printer_migrate_settings(struct net_context *c, int argc,
6736                                         const char **argv)
6737 {
6738         if (c->display_usage) {
6739                 d_printf(  "%s\n"
6740                            "net rpc printer migrate settings\n"
6741                             "    %s\n",
6742                           _("Usage:"),
6743                           _("Migrate printer-settings from a "
6744                             "print-server"));
6745                 return 0;
6746         }
6747
6748         if (!c->opt_host) {
6749                 d_printf(_("no server to migrate\n"));
6750                 return -1;
6751         }
6752
6753         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6754                                rpc_printer_migrate_settings_internals,
6755                                argc, argv);
6756 }
6757
6758 /**
6759  * 'net rpc printer' entrypoint.
6760  *
6761  * @param c     A net_context structure.
6762  * @param argc  Standard main() style argc.
6763  * @param argv  Standard main() style argv. Initial components are already
6764  *              stripped.
6765  **/
6766
6767 int rpc_printer_migrate(struct net_context *c, int argc, const char **argv)
6768 {
6769
6770         /* ouch: when addriver and setdriver are called from within
6771            rpc_printer_migrate_drivers_internals, the printer-queue already
6772            *has* to exist */
6773
6774         struct functable func[] = {
6775                 {
6776                         "all",
6777                         rpc_printer_migrate_all,
6778                         NET_TRANSPORT_RPC,
6779                         N_("Migrate all from remote to local print server"),
6780                         N_("net rpc printer migrate all\n"
6781                            "    Migrate all from remote to local print server")
6782                 },
6783                 {
6784                         "drivers",
6785                         rpc_printer_migrate_drivers,
6786                         NET_TRANSPORT_RPC,
6787                         N_("Migrate drivers to local server"),
6788                         N_("net rpc printer migrate drivers\n"
6789                            "    Migrate drivers to local server")
6790                 },
6791                 {
6792                         "forms",
6793                         rpc_printer_migrate_forms,
6794                         NET_TRANSPORT_RPC,
6795                         N_("Migrate froms to local server"),
6796                         N_("net rpc printer migrate forms\n"
6797                            "    Migrate froms to local server")
6798                 },
6799                 {
6800                         "printers",
6801                         rpc_printer_migrate_printers,
6802                         NET_TRANSPORT_RPC,
6803                         N_("Migrate printers to local server"),
6804                         N_("net rpc printer migrate printers\n"
6805                            "    Migrate printers to local server")
6806                 },
6807                 {
6808                         "security",
6809                         rpc_printer_migrate_security,
6810                         NET_TRANSPORT_RPC,
6811                         N_("Mirgate printer ACLs to local server"),
6812                         N_("net rpc printer migrate security\n"
6813                            "    Mirgate printer ACLs to local server")
6814                 },
6815                 {
6816                         "settings",
6817                         rpc_printer_migrate_settings,
6818                         NET_TRANSPORT_RPC,
6819                         N_("Migrate printer settings to local server"),
6820                         N_("net rpc printer migrate settings\n"
6821                            "    Migrate printer settings to local server")
6822                 },
6823                 {NULL, NULL, 0, NULL, NULL}
6824         };
6825
6826         return net_run_function(c, argc, argv, "net rpc printer migrate",func);
6827 }
6828
6829
6830 /**
6831  * List printers on a remote RPC server.
6832  *
6833  * @param c     A net_context structure.
6834  * @param argc  Standard main() style argc.
6835  * @param argv  Standard main() style argv. Initial components are already
6836  *              stripped.
6837  *
6838  * @return A shell status integer (0 for success).
6839  **/
6840 static int rpc_printer_list(struct net_context *c, int argc, const char **argv)
6841 {
6842         if (c->display_usage) {
6843                 d_printf(  "%s\n"
6844                            "net rpc printer list\n"
6845                            "    %s\n",
6846                          _("Usage:"),
6847                          _("List printers on a remote RPC server"));
6848                 return 0;
6849         }
6850
6851         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6852                                rpc_printer_list_internals,
6853                                argc, argv);
6854 }
6855
6856 /**
6857  * List printer-drivers on a remote RPC server.
6858  *
6859  * @param c     A net_context structure.
6860  * @param argc  Standard main() style argc.
6861  * @param argv  Standard main() style argv. Initial components are already
6862  *              stripped.
6863  *
6864  * @return A shell status integer (0 for success).
6865  **/
6866 static int rpc_printer_driver_list(struct net_context *c, int argc,
6867                                    const char **argv)
6868 {
6869         if (c->display_usage) {
6870                 d_printf(  "%s\n"
6871                            "net rpc printer driver\n"
6872                            "    %s\n",
6873                          _("Usage:"),
6874                          _("List printer-drivers on a remote RPC server"));
6875                 return 0;
6876         }
6877
6878         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6879                                rpc_printer_driver_list_internals,
6880                                argc, argv);
6881 }
6882
6883 /**
6884  * Publish printer in ADS via MSRPC.
6885  *
6886  * @param c     A net_context structure.
6887  * @param argc  Standard main() style argc.
6888  * @param argv  Standard main() style argv. Initial components are already
6889  *              stripped.
6890  *
6891  * @return A shell status integer (0 for success).
6892  **/
6893 static int rpc_printer_publish_publish(struct net_context *c, int argc,
6894                                        const char **argv)
6895 {
6896         if (c->display_usage) {
6897                 d_printf(  "%s\n"
6898                            "net rpc printer publish publish\n"
6899                            "     %s\n",
6900                          _("Usage:"),
6901                          _("Publish printer in ADS via MSRPC"));
6902                 return 0;
6903         }
6904
6905         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6906                                rpc_printer_publish_publish_internals,
6907                                argc, argv);
6908 }
6909
6910 /**
6911  * Update printer in ADS via MSRPC.
6912  *
6913  * @param c     A net_context structure.
6914  * @param argc  Standard main() style argc.
6915  * @param argv  Standard main() style argv. Initial components are already
6916  *              stripped.
6917  *
6918  * @return A shell status integer (0 for success).
6919  **/
6920 static int rpc_printer_publish_update(struct net_context *c, int argc, const char **argv)
6921 {
6922         if (c->display_usage) {
6923                 d_printf(  "%s\n"
6924                            "net rpc printer publish update\n"
6925                            "    %s\n",
6926                          _("Usage:"),
6927                          _("Update printer in ADS via MSRPC"));
6928                 return 0;
6929         }
6930
6931         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6932                                rpc_printer_publish_update_internals,
6933                                argc, argv);
6934 }
6935
6936 /**
6937  * UnPublish printer in ADS via MSRPC.
6938  *
6939  * @param c     A net_context structure.
6940  * @param argc  Standard main() style argc.
6941  * @param argv  Standard main() style argv. Initial components are already
6942  *              stripped.
6943  *
6944  * @return A shell status integer (0 for success).
6945  **/
6946 static int rpc_printer_publish_unpublish(struct net_context *c, int argc,
6947                                          const char **argv)
6948 {
6949         if (c->display_usage) {
6950                 d_printf(  "%s\n"
6951                            "net rpc printer publish unpublish\n"
6952                            "    %s\n",
6953                          _("Usage:\n"),
6954                          _("UnPublish printer in ADS via MSRPC"));
6955                 return 0;
6956         }
6957
6958         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6959                                rpc_printer_publish_unpublish_internals,
6960                                argc, argv);
6961 }
6962
6963 /**
6964  * List published printers via MSRPC.
6965  *
6966  * @param c     A net_context structure.
6967  * @param argc  Standard main() style argc.
6968  * @param argv  Standard main() style argv. Initial components are already
6969  *              stripped.
6970  *
6971  * @return A shell status integer (0 for success).
6972  **/
6973 static int rpc_printer_publish_list(struct net_context *c, int argc,
6974                                     const char **argv)
6975 {
6976         if (c->display_usage) {
6977                 d_printf(  "%s\n"
6978                            "net rpc printer publish list\n"
6979                            "    %s\n",
6980                          _("Usage:"),
6981                          _("List published printers via MSRPC"));
6982                 return 0;
6983         }
6984
6985         return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
6986                                rpc_printer_publish_list_internals,
6987                                argc, argv);
6988 }
6989
6990
6991 /**
6992  * Publish printer in ADS.
6993  *
6994  * @param c     A net_context structure.
6995  * @param argc  Standard main() style argc.
6996  * @param argv  Standard main() style argv. Initial components are already
6997  *              stripped.
6998  *
6999  * @return A shell status integer (0 for success).
7000  **/
7001 static int rpc_printer_publish(struct net_context *c, int argc,
7002                                const char **argv)
7003 {
7004
7005         struct functable func[] = {
7006                 {
7007                         "publish",
7008                         rpc_printer_publish_publish,
7009                         NET_TRANSPORT_RPC,
7010                         N_("Publish printer in AD"),
7011                         N_("net rpc printer publish publish\n"
7012                            "    Publish printer in AD")
7013                 },
7014                 {
7015                         "update",
7016                         rpc_printer_publish_update,
7017                         NET_TRANSPORT_RPC,
7018                         N_("Update printer in AD"),
7019                         N_("net rpc printer publish update\n"
7020                            "    Update printer in AD")
7021                 },
7022                 {
7023                         "unpublish",
7024                         rpc_printer_publish_unpublish,
7025                         NET_TRANSPORT_RPC,
7026                         N_("Unpublish printer"),
7027                         N_("net rpc printer publish unpublish\n"
7028                            "    Unpublish printer")
7029                 },
7030                 {
7031                         "list",
7032                         rpc_printer_publish_list,
7033                         NET_TRANSPORT_RPC,
7034                         N_("List published printers"),
7035                         N_("net rpc printer publish list\n"
7036                            "    List published printers")
7037                 },
7038                 {NULL, NULL, 0, NULL, NULL}
7039         };
7040
7041         if (argc == 0) {
7042                 if (c->display_usage) {
7043                         d_printf(_("Usage:\n"));
7044                         d_printf(_("net rpc printer publish\n"
7045                                    "    List published printers\n"
7046                                    "    Alias of net rpc printer publish "
7047                                    "list\n"));
7048                         net_display_usage_from_functable(func);
7049                         return 0;
7050                 }
7051                 return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
7052                                rpc_printer_publish_list_internals,
7053                                argc, argv);
7054         }
7055
7056         return net_run_function(c, argc, argv, "net rpc printer publish",func);
7057
7058 }
7059
7060
7061 /**
7062  * Display rpc printer help page.
7063  *
7064  * @param c     A net_context structure.
7065  * @param argc  Standard main() style argc.
7066  * @param argv  Standard main() style argv. Initial components are already
7067  *              stripped.
7068  **/
7069 int rpc_printer_usage(struct net_context *c, int argc, const char **argv)
7070 {
7071         d_printf(_("net rpc printer LIST [printer] [misc. options] [targets]\n"
7072                    "\tlists all printers on print-server\n\n"));
7073         d_printf(_("net rpc printer DRIVER [printer] [misc. options] [targets]\n"
7074                    "\tlists all printer-drivers on print-server\n\n"));
7075         d_printf(_("net rpc printer PUBLISH action [printer] [misc. options] [targets]\n"
7076                    "\tpublishes printer settings in Active Directory\n"
7077                    "\taction can be one of PUBLISH, UPDATE, UNPUBLISH or LIST\n\n"));
7078         d_printf(_("net rpc printer MIGRATE PRINTERS [printer] [misc. options] [targets]"
7079                    "\n\tmigrates printers from remote to local server\n\n"));
7080         d_printf(_("net rpc printer MIGRATE SETTINGS [printer] [misc. options] [targets]"
7081                    "\n\tmigrates printer-settings from remote to local server\n\n"));
7082         d_printf(_("net rpc printer MIGRATE DRIVERS [printer] [misc. options] [targets]"
7083                    "\n\tmigrates printer-drivers from remote to local server\n\n"));
7084         d_printf(_("net rpc printer MIGRATE FORMS [printer] [misc. options] [targets]"
7085                    "\n\tmigrates printer-forms from remote to local server\n\n"));
7086         d_printf(_("net rpc printer MIGRATE SECURITY [printer] [misc. options] [targets]"
7087                    "\n\tmigrates printer-ACLs from remote to local server\n\n"));
7088         d_printf(_("net rpc printer MIGRATE ALL [printer] [misc. options] [targets]"
7089                    "\n\tmigrates drivers, forms, queues, settings and acls from\n"
7090                    "\tremote to local print-server\n\n"));
7091         net_common_methods_usage(c, argc, argv);
7092         net_common_flags_usage(c, argc, argv);
7093         d_printf(_(
7094          "\t-v or --verbose\t\t\tgive verbose output\n"
7095          "\t      --destination\t\tmigration target server (default: localhost)\n"));
7096
7097         return -1;
7098 }
7099
7100 /**
7101  * 'net rpc printer' entrypoint.
7102  *
7103  * @param c     A net_context structure.
7104  * @param argc  Standard main() style argc.
7105  * @param argv  Standard main() style argv. Initial components are already
7106  *              stripped.
7107  **/
7108 int net_rpc_printer(struct net_context *c, int argc, const char **argv)
7109 {
7110         struct functable func[] = {
7111                 {
7112                         "list",
7113                         rpc_printer_list,
7114                         NET_TRANSPORT_RPC,
7115                         N_("List all printers on print server"),
7116                         N_("net rpc printer list\n"
7117                            "    List all printers on print server")
7118                 },
7119                 {
7120                         "migrate",
7121                         rpc_printer_migrate,
7122                         NET_TRANSPORT_RPC,
7123                         N_("Migrate printer to local server"),
7124                         N_("net rpc printer migrate\n"
7125                            "    Migrate printer to local server")
7126                 },
7127                 {
7128                         "driver",
7129                         rpc_printer_driver_list,
7130                         NET_TRANSPORT_RPC,
7131                         N_("List printer drivers"),
7132                         N_("net rpc printer driver\n"
7133                            "    List printer drivers")
7134                 },
7135                 {
7136                         "publish",
7137                         rpc_printer_publish,
7138                         NET_TRANSPORT_RPC,
7139                         N_("Publish printer in AD"),
7140                         N_("net rpc printer publish\n"
7141                            "    Publish printer in AD")
7142                 },
7143                 {NULL, NULL, 0, NULL, NULL}
7144         };
7145
7146         if (argc == 0) {
7147                 if (c->display_usage) {
7148                         d_printf(_("Usage:\n"));
7149                         d_printf(_("net rpc printer\n"
7150                                    "    List printers\n"));
7151                         net_display_usage_from_functable(func);
7152                         return 0;
7153                 }
7154                 return run_rpc_command(c, NULL, &ndr_table_spoolss.syntax_id, 0,
7155                                rpc_printer_list_internals,
7156                                argc, argv);
7157         }
7158
7159         return net_run_function(c, argc, argv, "net rpc printer", func);
7160 }
7161
7162 /**
7163  * 'net rpc' entrypoint.
7164  *
7165  * @param c     A net_context structure.
7166  * @param argc  Standard main() style argc.
7167  * @param argv  Standard main() style argv. Initial components are already
7168  *              stripped.
7169  **/
7170
7171 int net_rpc(struct net_context *c, int argc, const char **argv)
7172 {
7173         NET_API_STATUS status;
7174
7175         struct functable func[] = {
7176                 {
7177                         "audit",
7178                         net_rpc_audit,
7179                         NET_TRANSPORT_RPC,
7180                         N_("Modify global audit settings"),
7181                         N_("net rpc audit\n"
7182                            "    Modify global audit settings")
7183                 },
7184                 {
7185                         "info",
7186                         net_rpc_info,
7187                         NET_TRANSPORT_RPC,
7188                         N_("Show basic info about a domain"),
7189                         N_("net rpc info\n"
7190                            "    Show basic info about a domain")
7191                 },
7192                 {
7193                         "join",
7194                         net_rpc_join,
7195                         NET_TRANSPORT_RPC,
7196                         N_("Join a domain"),
7197                         N_("net rpc join\n"
7198                            "    Join a domain")
7199                 },
7200                 {
7201                         "oldjoin",
7202                         net_rpc_oldjoin,
7203                         NET_TRANSPORT_RPC,
7204                         N_("Join a domain created in server manager"),
7205                         N_("net rpc oldjoin\n"
7206                            "    Join a domain created in server manager")
7207                 },
7208                 {
7209                         "testjoin",
7210                         net_rpc_testjoin,
7211                         NET_TRANSPORT_RPC,
7212                         N_("Test that a join is valid"),
7213                         N_("net rpc testjoin\n"
7214                            "    Test that a join is valid")
7215                 },
7216                 {
7217                         "user",
7218                         net_rpc_user,
7219                         NET_TRANSPORT_RPC,
7220                         N_("List/modify users"),
7221                         N_("net rpc user\n"
7222                            "    List/modify users")
7223                 },
7224                 {
7225                         "password",
7226                         rpc_user_password,
7227                         NET_TRANSPORT_RPC,
7228                         N_("Change a user password"),
7229                         N_("net rpc password\n"
7230                            "    Change a user password\n"
7231                            "    Alias for net rpc user password")
7232                 },
7233                 {
7234                         "group",
7235                         net_rpc_group,
7236                         NET_TRANSPORT_RPC,
7237                         N_("List/modify groups"),
7238                         N_("net rpc group\n"
7239                            "    List/modify groups")
7240                 },
7241                 {
7242                         "share",
7243                         net_rpc_share,
7244                         NET_TRANSPORT_RPC,
7245                         N_("List/modify shares"),
7246                         N_("net rpc share\n"
7247                            "    List/modify shares")
7248                 },
7249                 {
7250                         "file",
7251                         net_rpc_file,
7252                         NET_TRANSPORT_RPC,
7253                         N_("List open files"),
7254                         N_("net rpc file\n"
7255                            "    List open files")
7256                 },
7257                 {
7258                         "printer",
7259                         net_rpc_printer,
7260                         NET_TRANSPORT_RPC,
7261                         N_("List/modify printers"),
7262                         N_("net rpc printer\n"
7263                            "    List/modify printers")
7264                 },
7265                 {
7266                         "changetrustpw",
7267                         net_rpc_changetrustpw,
7268                         NET_TRANSPORT_RPC,
7269                         N_("Change trust account password"),
7270                         N_("net rpc changetrustpw\n"
7271                            "    Change trust account password")
7272                 },
7273                 {
7274                         "trustdom",
7275                         rpc_trustdom,
7276                         NET_TRANSPORT_RPC,
7277                         N_("Modify domain trusts"),
7278                         N_("net rpc trustdom\n"
7279                            "    Modify domain trusts")
7280                 },
7281                 {
7282                         "abortshutdown",
7283                         rpc_shutdown_abort,
7284                         NET_TRANSPORT_RPC,
7285                         N_("Abort a remote shutdown"),
7286                         N_("net rpc abortshutdown\n"
7287                            "    Abort a remote shutdown")
7288                 },
7289                 {
7290                         "shutdown",
7291                         rpc_shutdown,
7292                         NET_TRANSPORT_RPC,
7293                         N_("Shutdown a remote server"),
7294                         N_("net rpc shutdown\n"
7295                            "    Shutdown a remote server")
7296                 },
7297                 {
7298                         "samdump",
7299                         rpc_samdump,
7300                         NET_TRANSPORT_RPC,
7301                         N_("Dump SAM data of remote NT PDC"),
7302                         N_("net rpc samdump\n"
7303                            "    Dump SAM data of remote NT PDC")
7304                 },
7305                 {
7306                         "vampire",
7307                         rpc_vampire,
7308                         NET_TRANSPORT_RPC,
7309                         N_("Sync a remote NT PDC's data into local passdb"),
7310                         N_("net rpc vampire\n"
7311                            "    Sync a remote NT PDC's data into local passdb")
7312                 },
7313                 {
7314                         "getsid",
7315                         net_rpc_getsid,
7316                         NET_TRANSPORT_RPC,
7317                         N_("Fetch the domain sid into local secrets.tdb"),
7318                         N_("net rpc getsid\n"
7319                            "    Fetch the domain sid into local secrets.tdb")
7320                 },
7321                 {
7322                         "rights",
7323                         net_rpc_rights,
7324                         NET_TRANSPORT_RPC,
7325                         N_("Manage privileges assigned to SID"),
7326                         N_("net rpc rights\n"
7327                            "    Manage privileges assigned to SID")
7328                 },
7329                 {
7330                         "service",
7331                         net_rpc_service,
7332                         NET_TRANSPORT_RPC,
7333                         N_("Start/stop/query remote services"),
7334                         N_("net rpc service\n"
7335                            "    Start/stop/query remote services")
7336                 },
7337                 {
7338                         "registry",
7339                         net_rpc_registry,
7340                         NET_TRANSPORT_RPC,
7341                         N_("Manage registry hives"),
7342                         N_("net rpc registry\n"
7343                            "    Manage registry hives")
7344                 },
7345                 {
7346                         "shell",
7347                         net_rpc_shell,
7348                         NET_TRANSPORT_RPC,
7349                         N_("Open interactive shell on remote server"),
7350                         N_("net rpc shell\n"
7351                            "    Open interactive shell on remote server")
7352                 },
7353                 {NULL, NULL, 0, NULL, NULL}
7354         };
7355
7356         status = libnetapi_init(&c->netapi_ctx);
7357         if (status != 0) {
7358                 return -1;
7359         }
7360         libnetapi_set_username(c->netapi_ctx, c->opt_user_name);
7361         libnetapi_set_password(c->netapi_ctx, c->opt_password);
7362         if (c->opt_kerberos) {
7363                 libnetapi_set_use_kerberos(c->netapi_ctx);
7364         }
7365
7366         return net_run_function(c, argc, argv, "net rpc", func);
7367 }