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