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