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