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