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