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