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