r2935: This is a long-standing one in my patch-queue: A pair of net commands
[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
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20  
21 #include "includes.h"
22 #include "utils/net.h"
23
24 /**
25  * @file net_rpc.c
26  *
27  * @brief RPC based subcommands for the 'net' utility.
28  *
29  * This file should contain much of the functionality that used to
30  * be found in rpcclient, execpt that the commands should change 
31  * less often, and the fucntionality should be sane (the user is not 
32  * expected to know a rid/sid before they conduct an operation etc.)
33  *
34  * @todo Perhaps eventually these should be split out into a number
35  * of files, as this could get quite big.
36  **/
37
38
39 /* A function of this type is passed to the 'run_rpc_command' wrapper */
40 typedef NTSTATUS (*rpc_command_fn)(const DOM_SID *, const char *, 
41                                    struct cli_state *, TALLOC_CTX *, int, const char **);
42
43 /**
44  * Many of the RPC functions need the domain sid.  This function gets
45  *  it at the start of every run 
46  *
47  * @param cli A cli_state already connected to the remote machine
48  *
49  * @return The Domain SID of the remote machine.
50  **/
51
52 static DOM_SID *net_get_remote_domain_sid(struct cli_state *cli, TALLOC_CTX *mem_ctx, char **domain_name)
53 {
54         DOM_SID *domain_sid;
55         POLICY_HND pol;
56         NTSTATUS result = NT_STATUS_OK;
57         uint32 info_class = 5;
58         
59         if (!cli_nt_session_open (cli, PI_LSARPC)) {
60                 fprintf(stderr, "could not initialise lsa pipe\n");
61                 goto error;
62         }
63         
64         result = cli_lsa_open_policy(cli, mem_ctx, False, 
65                                      SEC_RIGHTS_MAXIMUM_ALLOWED,
66                                      &pol);
67         if (!NT_STATUS_IS_OK(result)) {
68                 goto error;
69         }
70
71         result = cli_lsa_query_info_policy(cli, mem_ctx, &pol, info_class, 
72                                            domain_name, &domain_sid);
73         if (!NT_STATUS_IS_OK(result)) {
74  error:
75                 fprintf(stderr, "could not obtain sid for domain %s\n", cli->domain);
76
77                 if (!NT_STATUS_IS_OK(result)) {
78                         fprintf(stderr, "error: %s\n", nt_errstr(result));
79                 }
80
81                 exit(1);
82         }
83
84         cli_lsa_close(cli, mem_ctx, &pol);
85         cli_nt_session_close(cli);
86
87         return domain_sid;
88 }
89
90 /**
91  * Run a single RPC command, from start to finish.
92  *
93  * @param pipe_name the pipe to connect to (usually a PIPE_ constant)
94  * @param conn_flag a NET_FLAG_ combination.  Passed to 
95  *                   net_make_ipc_connection.
96  * @param argc  Standard main() style argc
97  * @param argc  Standard main() style argv.  Initial components are already
98  *              stripped
99  * @return A shell status integer (0 for success)
100  */
101
102 static int run_rpc_command(struct cli_state *cli_arg, const int pipe_idx, int conn_flags,
103                            rpc_command_fn fn,
104                            int argc, const char **argv) 
105 {
106         struct cli_state *cli = NULL;
107         TALLOC_CTX *mem_ctx;
108         NTSTATUS nt_status;
109         DOM_SID *domain_sid;
110         char *domain_name;
111
112         /* make use of cli_state handed over as an argument, if possible */
113         if (!cli_arg)
114                 cli = net_make_ipc_connection(conn_flags);
115         else
116                 cli = cli_arg;
117
118         if (!cli) {
119                 return -1;
120         }
121
122         /* Create mem_ctx */
123         
124         if (!(mem_ctx = talloc_init("run_rpc_command"))) {
125                 DEBUG(0, ("talloc_init() failed\n"));
126                 cli_shutdown(cli);
127                 return -1;
128         }
129         
130         domain_sid = net_get_remote_domain_sid(cli, mem_ctx, &domain_name);
131
132         if (!(conn_flags & NET_FLAGS_NO_PIPE)) {
133                 if (!cli_nt_session_open(cli, pipe_idx)) {
134                         DEBUG(0, ("Could not initialise pipe\n"));
135                 }
136         }
137         
138         nt_status = fn(domain_sid, domain_name, cli, mem_ctx, argc, argv);
139         
140         if (!NT_STATUS_IS_OK(nt_status)) {
141                 DEBUG(1, ("rpc command function failed! (%s)\n", nt_errstr(nt_status)));
142         } else {
143                 DEBUG(5, ("rpc command function succedded\n"));
144         }
145                 
146         if (!(conn_flags & NET_FLAGS_NO_PIPE)) {
147                 if (cli->nt_pipe_fnum)
148                         cli_nt_session_close(cli);
149         }
150
151         /* close the connection only if it was opened here */
152         if (!cli_arg)
153                 cli_shutdown(cli);
154         
155         talloc_destroy(mem_ctx);
156
157         return (!NT_STATUS_IS_OK(nt_status));
158 }
159
160
161 /****************************************************************************/
162
163
164 /** 
165  * Force a change of the trust acccount password.
166  *
167  * All parameters are provided by the run_rpc_command function, except for
168  * argc, argv which are passes through. 
169  *
170  * @param domain_sid The domain sid aquired from the remote server
171  * @param cli A cli_state connected to the server.
172  * @param mem_ctx Talloc context, destoyed on compleation of the function.
173  * @param argc  Standard main() style argc
174  * @param argc  Standard main() style argv.  Initial components are already
175  *              stripped
176  *
177  * @return Normal NTSTATUS return.
178  **/
179
180 static NTSTATUS rpc_changetrustpw_internals(const DOM_SID *domain_sid, const char *domain_name, 
181                                             struct cli_state *cli, TALLOC_CTX *mem_ctx, 
182                                             int argc, const char **argv) {
183         
184         return trust_pw_find_change_and_store_it(cli, mem_ctx, opt_target_workgroup);
185 }
186
187 /** 
188  * Force a change of the trust acccount password.
189  *
190  * @param argc  Standard main() style argc
191  * @param argc  Standard main() style argv.  Initial components are already
192  *              stripped
193  *
194  * @return A shell status integer (0 for success)
195  **/
196
197 int net_rpc_changetrustpw(int argc, const char **argv) 
198 {
199         return run_rpc_command(NULL, PI_NETLOGON, NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC, 
200                                rpc_changetrustpw_internals,
201                                argc, argv);
202 }
203
204
205 /****************************************************************************/
206
207
208 /** 
209  * Join a domain, the old way.
210  *
211  * This uses 'machinename' as the inital password, and changes it. 
212  *
213  * The password should be created with 'server manager' or equiv first.
214  *
215  * All parameters are provided by the run_rpc_command function, except for
216  * argc, argv which are passes through. 
217  *
218  * @param domain_sid The domain sid aquired from the remote server
219  * @param cli A cli_state connected to the server.
220  * @param mem_ctx Talloc context, destoyed on compleation of the function.
221  * @param argc  Standard main() style argc
222  * @param argc  Standard main() style argv.  Initial components are already
223  *              stripped
224  *
225  * @return Normal NTSTATUS return.
226  **/
227
228 static NTSTATUS rpc_oldjoin_internals(const DOM_SID *domain_sid, const char *domain_name, 
229                                       struct cli_state *cli, 
230                                       TALLOC_CTX *mem_ctx, 
231                                       int argc, const char **argv) {
232         
233         fstring trust_passwd;
234         unsigned char orig_trust_passwd_hash[16];
235         NTSTATUS result;
236         uint32 sec_channel_type;
237
238         /* 
239            check what type of join - if the user want's to join as
240            a BDC, the server must agree that we are a BDC.
241         */
242         if (argc >= 0) {
243                 sec_channel_type = get_sec_channel_type(argv[0]);
244         } else {
245                 sec_channel_type = get_sec_channel_type(NULL);
246         }
247         
248         fstrcpy(trust_passwd, global_myname());
249         strlower_m(trust_passwd);
250
251         /*
252          * Machine names can be 15 characters, but the max length on
253          * a password is 14.  --jerry
254          */
255
256         trust_passwd[14] = '\0';
257
258         E_md4hash(trust_passwd, orig_trust_passwd_hash);
259
260         result = trust_pw_change_and_store_it(cli, mem_ctx, opt_target_workgroup,
261                                               orig_trust_passwd_hash,
262                                               sec_channel_type);
263
264         if (NT_STATUS_IS_OK(result))
265                 printf("Joined domain %s.\n",opt_target_workgroup);
266
267
268         if (!secrets_store_domain_sid(opt_target_workgroup, domain_sid)) {
269                 DEBUG(0, ("error storing domain sid for %s\n", opt_target_workgroup));
270                 result = NT_STATUS_UNSUCCESSFUL;
271         }
272
273         return result;
274 }
275
276 /** 
277  * Join a domain, the old way.
278  *
279  * @param argc  Standard main() style argc
280  * @param argc  Standard main() style argv.  Initial components are already
281  *              stripped
282  *
283  * @return A shell status integer (0 for success)
284  **/
285
286 static int net_rpc_perform_oldjoin(int argc, const char **argv)
287 {
288         return run_rpc_command(NULL, PI_NETLOGON, 
289                                NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC, 
290                                rpc_oldjoin_internals,
291                                argc, argv);
292 }
293
294 /** 
295  * Join a domain, the old way.  This function exists to allow
296  * the message to be displayed when oldjoin was explicitly 
297  * requested, but not when it was implied by "net rpc join"
298  *
299  * @param argc  Standard main() style argc
300  * @param argc  Standard main() style argv.  Initial components are already
301  *              stripped
302  *
303  * @return A shell status integer (0 for success)
304  **/
305
306 static int net_rpc_oldjoin(int argc, const char **argv) 
307 {
308         int rc = net_rpc_perform_oldjoin(argc, argv);
309
310         if (rc) {
311                 d_printf("Failed to join domain\n");
312         }
313
314         return rc;
315 }
316
317 /** 
318  * Basic usage function for 'net rpc join'
319  * @param argc  Standard main() style argc
320  * @param argc  Standard main() style argv.  Initial components are already
321  *              stripped
322  **/
323
324 static int rpc_join_usage(int argc, const char **argv) 
325 {       
326         d_printf("net rpc join -U <username>[%%password] <type>[options]\n"\
327                  "\t to join a domain with admin username & password\n"\
328                  "\t\t password will be prompted if needed and none is specified\n"\
329                  "\t <type> can be (default MEMBER)\n"\
330                  "\t\t BDC - Join as a BDC\n"\
331                  "\t\t PDC - Join as a PDC\n"\
332                  "\t\t MEMBER - Join as a MEMBER server\n");
333
334         net_common_flags_usage(argc, argv);
335         return -1;
336 }
337
338 /** 
339  * 'net rpc join' entrypoint.
340  * @param argc  Standard main() style argc
341  * @param argc  Standard main() style argv.  Initial components are already
342  *              stripped
343  *
344  * Main 'net_rpc_join()' (where the admain username/password is used) is 
345  * in net_rpc_join.c
346  * Try to just change the password, but if that doesn't work, use/prompt
347  * for a username/password.
348  **/
349
350 int net_rpc_join(int argc, const char **argv) 
351 {
352         if ((net_rpc_perform_oldjoin(argc, argv) == 0))
353                 return 0;
354         
355         return net_rpc_join_newstyle(argc, argv);
356 }
357
358
359
360 /** 
361  * display info about a rpc domain
362  *
363  * All parameters are provided by the run_rpc_command function, except for
364  * argc, argv which are passed through. 
365  *
366  * @param domain_sid The domain sid acquired from the remote server
367  * @param cli A cli_state connected to the server.
368  * @param mem_ctx Talloc context, destoyed on completion of the function.
369  * @param argc  Standard main() style argc
370  * @param argv  Standard main() style argv.  Initial components are already
371  *              stripped
372  *
373  * @return Normal NTSTATUS return.
374  **/
375
376 static NTSTATUS 
377 rpc_info_internals(const DOM_SID *domain_sid, const char *domain_name, 
378                    struct cli_state *cli,
379                    TALLOC_CTX *mem_ctx, int argc, const char **argv)
380 {
381         POLICY_HND connect_pol, domain_pol;
382         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
383         SAM_UNK_CTR ctr;
384         fstring sid_str;
385
386         sid_to_string(sid_str, domain_sid);
387
388         /* Get sam policy handle */     
389         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
390                                   &connect_pol);
391         if (!NT_STATUS_IS_OK(result)) {
392                 goto done;
393         }
394         
395         /* Get domain policy handle */
396         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
397                                       MAXIMUM_ALLOWED_ACCESS,
398                                       domain_sid, &domain_pol);
399         if (!NT_STATUS_IS_OK(result)) {
400                 goto done;
401         }
402
403         ZERO_STRUCT(ctr);
404         result = cli_samr_query_dom_info(cli, mem_ctx, &domain_pol,
405                                          2, &ctr);
406         if (NT_STATUS_IS_OK(result)) {
407                 TALLOC_CTX *ctx = talloc_init("rpc_info_internals");
408                 d_printf("Domain Name: %s\n", unistr2_tdup(ctx, &ctr.info.inf2.uni_domain));
409                 d_printf("Domain SID: %s\n", sid_str);
410                 d_printf("Sequence number: %u\n", ctr.info.inf2.seq_num);
411                 d_printf("Num users: %u\n", ctr.info.inf2.num_domain_usrs);
412                 d_printf("Num domain groups: %u\n", ctr.info.inf2.num_domain_grps);
413                 d_printf("Num local groups: %u\n", ctr.info.inf2.num_local_grps);
414                 talloc_destroy(ctx);
415         }
416
417  done:
418         return result;
419 }
420
421
422 /** 
423  * 'net rpc info' entrypoint.
424  * @param argc  Standard main() style argc
425  * @param argc  Standard main() style argv.  Initial components are already
426  *              stripped
427  **/
428 int net_rpc_info(int argc, const char **argv) 
429 {
430         return run_rpc_command(NULL, PI_SAMR, NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC, 
431                                rpc_info_internals,
432                                argc, argv);
433 }
434
435
436 /** 
437  * Fetch domain SID into the local secrets.tdb
438  *
439  * All parameters are provided by the run_rpc_command function, except for
440  * argc, argv which are passes through. 
441  *
442  * @param domain_sid The domain sid acquired from the remote server
443  * @param cli A cli_state connected to the server.
444  * @param mem_ctx Talloc context, destoyed on completion of the function.
445  * @param argc  Standard main() style argc
446  * @param argv  Standard main() style argv.  Initial components are already
447  *              stripped
448  *
449  * @return Normal NTSTATUS return.
450  **/
451
452 static NTSTATUS 
453 rpc_getsid_internals(const DOM_SID *domain_sid, const char *domain_name, 
454                      struct cli_state *cli,
455                      TALLOC_CTX *mem_ctx, int argc, const char **argv)
456 {
457         fstring sid_str;
458
459         sid_to_string(sid_str, domain_sid);
460         d_printf("Storing SID %s for Domain %s in secrets.tdb\n",
461                  sid_str, domain_name);
462
463         if (!secrets_store_domain_sid(domain_name, domain_sid)) {
464                 DEBUG(0,("Can't store domain SID\n"));
465                 return NT_STATUS_UNSUCCESSFUL;
466         }
467
468         return NT_STATUS_OK;
469 }
470
471
472 /** 
473  * 'net rpc getsid' entrypoint.
474  * @param argc  Standard main() style argc
475  * @param argc  Standard main() style argv.  Initial components are already
476  *              stripped
477  **/
478 int net_rpc_getsid(int argc, const char **argv) 
479 {
480         return run_rpc_command(NULL, PI_SAMR, NET_FLAGS_ANONYMOUS | NET_FLAGS_PDC, 
481                                rpc_getsid_internals,
482                                argc, argv);
483 }
484
485
486 /****************************************************************************/
487
488 /**
489  * Basic usage function for 'net rpc user'
490  * @param argc  Standard main() style argc.
491  * @param argv  Standard main() style argv.  Initial components are already
492  *              stripped.
493  **/
494
495 static int rpc_user_usage(int argc, const char **argv)
496 {
497         return net_help_user(argc, argv);
498 }
499
500 /** 
501  * Add a new user to a remote RPC server
502  *
503  * All parameters are provided by the run_rpc_command function, except for
504  * argc, argv which are passes through. 
505  *
506  * @param domain_sid The domain sid acquired from the remote server
507  * @param cli A cli_state connected to the server.
508  * @param mem_ctx Talloc context, destoyed on completion of the function.
509  * @param argc  Standard main() style argc
510  * @param argv  Standard main() style argv.  Initial components are already
511  *              stripped
512  *
513  * @return Normal NTSTATUS return.
514  **/
515
516 static NTSTATUS rpc_user_add_internals(const DOM_SID *domain_sid, const char *domain_name, 
517                                        struct cli_state *cli, TALLOC_CTX *mem_ctx, 
518                                        int argc, const char **argv) {
519         
520         POLICY_HND connect_pol, domain_pol, user_pol;
521         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
522         const char *acct_name;
523         uint16 acb_info;
524         uint32 unknown, user_rid;
525
526         if (argc != 1) {
527                 d_printf("User must be specified\n");
528                 rpc_user_usage(argc, argv);
529                 return NT_STATUS_OK;
530         }
531
532         acct_name = argv[0];
533
534         /* Get sam policy handle */
535         
536         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
537                                   &connect_pol);
538         if (!NT_STATUS_IS_OK(result)) {
539                 goto done;
540         }
541         
542         /* Get domain policy handle */
543         
544         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
545                                       MAXIMUM_ALLOWED_ACCESS,
546                                       domain_sid, &domain_pol);
547         if (!NT_STATUS_IS_OK(result)) {
548                 goto done;
549         }
550
551         /* Create domain user */
552
553         acb_info = ACB_NORMAL;
554         unknown = 0xe005000b; /* No idea what this is - a permission mask? */
555
556         result = cli_samr_create_dom_user(cli, mem_ctx, &domain_pol,
557                                           acct_name, acb_info, unknown,
558                                           &user_pol, &user_rid);
559         if (!NT_STATUS_IS_OK(result)) {
560                 goto done;
561         }
562
563  done:
564         if (!NT_STATUS_IS_OK(result)) {
565                 d_printf("Failed to add user %s - %s\n", acct_name, 
566                          nt_errstr(result));
567         } else {
568                 d_printf("Added user %s\n", acct_name);
569         }
570         return result;
571 }
572
573 /** 
574  * Add a new user to a remote RPC server
575  *
576  * @param argc  Standard main() style argc
577  * @param argv  Standard main() style argv.  Initial components are already
578  *              stripped
579  *
580  * @return A shell status integer (0 for success)
581  **/
582
583 static int rpc_user_add(int argc, const char **argv) 
584 {
585         return run_rpc_command(NULL, PI_SAMR, 0, rpc_user_add_internals,
586                                argc, argv);
587 }
588
589 /** 
590  * Delete a user from a remote RPC server
591  *
592  * All parameters are provided by the run_rpc_command function, except for
593  * argc, argv which are passes through. 
594  *
595  * @param domain_sid The domain sid acquired from the remote server
596  * @param cli A cli_state connected to the server.
597  * @param mem_ctx Talloc context, destoyed on completion of the function.
598  * @param argc  Standard main() style argc
599  * @param argv  Standard main() style argv.  Initial components are already
600  *              stripped
601  *
602  * @return Normal NTSTATUS return.
603  **/
604
605 static NTSTATUS rpc_user_del_internals(const DOM_SID *domain_sid, 
606                                        const char *domain_name, 
607                                        struct cli_state *cli, 
608                                        TALLOC_CTX *mem_ctx, 
609                                        int argc, const char **argv)
610 {
611         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
612         POLICY_HND connect_pol, domain_pol, user_pol;
613
614         if (argc < 1) {
615                 d_printf("User must be specified\n");
616                 rpc_user_usage(argc, argv);
617                 return NT_STATUS_OK;
618         }
619         /* Get sam policy and domain handles */
620
621         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
622                                   &connect_pol);
623
624         if (!NT_STATUS_IS_OK(result)) {
625                 goto done;
626         }
627
628         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
629                                       MAXIMUM_ALLOWED_ACCESS,
630                                       domain_sid, &domain_pol);
631
632         if (!NT_STATUS_IS_OK(result)) {
633                 goto done;
634         }
635
636         /* Get handle on user */
637
638         {
639                 uint32 *user_rids, num_rids, *name_types;
640                 uint32 flags = 0x000003e8; /* Unknown */
641
642                 result = cli_samr_lookup_names(cli, mem_ctx, &domain_pol,
643                                                flags, 1, &argv[0],
644                                                &num_rids, &user_rids,
645                                                &name_types);
646
647                 if (!NT_STATUS_IS_OK(result)) {
648                         goto done;
649                 }
650
651                 result = cli_samr_open_user(cli, mem_ctx, &domain_pol,
652                                             MAXIMUM_ALLOWED_ACCESS,
653                                             user_rids[0], &user_pol);
654
655                 if (!NT_STATUS_IS_OK(result)) {
656                         goto done;
657                 }
658         }
659
660         /* Delete user */
661
662         result = cli_samr_delete_dom_user(cli, mem_ctx, &user_pol);
663
664         if (!NT_STATUS_IS_OK(result)) {
665                 goto done;
666         }
667
668         /* Display results */
669
670  done:
671         return result;
672
673 }       
674
675 /** 
676  * Delete a user from a remote RPC server
677  *
678  * @param argc  Standard main() style argc
679  * @param argv  Standard main() style argv.  Initial components are already
680  *              stripped
681  *
682  * @return A shell status integer (0 for success)
683  **/
684
685 static int rpc_user_delete(int argc, const char **argv) 
686 {
687         return run_rpc_command(NULL, PI_SAMR, 0, rpc_user_del_internals,
688                                argc, argv);
689 }
690
691 /** 
692  * Set a password for a user on a remote RPC server
693  *
694  * All parameters are provided by the run_rpc_command function, except for
695  * argc, argv which are passes through. 
696  *
697  * @param domain_sid The domain sid acquired from the remote server
698  * @param cli A cli_state connected to the server.
699  * @param mem_ctx Talloc context, destoyed on completion of the function.
700  * @param argc  Standard main() style argc
701  * @param argv  Standard main() style argv.  Initial components are already
702  *              stripped
703  *
704  * @return Normal NTSTATUS return.
705  **/
706
707 static NTSTATUS rpc_user_password_internals(const DOM_SID *domain_sid, 
708                                             const char *domain_name, 
709                                             struct cli_state *cli, 
710                                             TALLOC_CTX *mem_ctx, 
711                                             int argc, const char **argv)
712 {
713         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
714         POLICY_HND connect_pol, domain_pol, user_pol;
715         SAM_USERINFO_CTR ctr;
716         SAM_USER_INFO_24 p24;
717         uchar pwbuf[516];
718         const char *user;
719         const char *new_password;
720         char *prompt = NULL;
721
722         if (argc < 1) {
723                 d_printf("User must be specified\n");
724                 rpc_user_usage(argc, argv);
725                 return NT_STATUS_OK;
726         }
727         
728         user = argv[0];
729
730         if (argv[1]) {
731                 new_password = argv[1];
732         } else {
733                 asprintf(&prompt, "Enter new password for %s:", user);
734                 new_password = getpass(prompt);
735                 SAFE_FREE(prompt);
736         }
737
738         /* Get sam policy and domain handles */
739
740         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
741                                   &connect_pol);
742
743         if (!NT_STATUS_IS_OK(result)) {
744                 goto done;
745         }
746
747         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
748                                       MAXIMUM_ALLOWED_ACCESS,
749                                       domain_sid, &domain_pol);
750
751         if (!NT_STATUS_IS_OK(result)) {
752                 goto done;
753         }
754
755         /* Get handle on user */
756
757         {
758                 uint32 *user_rids, num_rids, *name_types;
759                 uint32 flags = 0x000003e8; /* Unknown */
760
761                 result = cli_samr_lookup_names(cli, mem_ctx, &domain_pol,
762                                                flags, 1, &user,
763                                                &num_rids, &user_rids,
764                                                &name_types);
765
766                 if (!NT_STATUS_IS_OK(result)) {
767                         goto done;
768                 }
769
770                 result = cli_samr_open_user(cli, mem_ctx, &domain_pol,
771                                             MAXIMUM_ALLOWED_ACCESS,
772                                             user_rids[0], &user_pol);
773
774                 if (!NT_STATUS_IS_OK(result)) {
775                         goto done;
776                 }
777         }
778
779         /* Set password on account */
780
781         ZERO_STRUCT(ctr);
782         ZERO_STRUCT(p24);
783
784         encode_pw_buffer(pwbuf, new_password, STR_UNICODE);
785
786         init_sam_user_info24(&p24, (char *)pwbuf,24);
787
788         ctr.switch_value = 24;
789         ctr.info.id24 = &p24;
790
791         result = cli_samr_set_userinfo(cli, mem_ctx, &user_pol, 24, 
792                                        &cli->user_session_key, &ctr);
793
794         if (!NT_STATUS_IS_OK(result)) {
795                 goto done;
796         }
797
798         /* Display results */
799
800  done:
801         return result;
802
803 }       
804
805 /** 
806  * Set a user's password on a remote RPC server
807  *
808  * @param argc  Standard main() style argc
809  * @param argv  Standard main() style argv.  Initial components are already
810  *              stripped
811  *
812  * @return A shell status integer (0 for success)
813  **/
814
815 static int rpc_user_password(int argc, const char **argv) 
816 {
817         return run_rpc_command(NULL, PI_SAMR, 0, rpc_user_password_internals,
818                                argc, argv);
819 }
820
821 /** 
822  * List user's groups on a remote RPC server
823  *
824  * All parameters are provided by the run_rpc_command function, except for
825  * argc, argv which are passes through. 
826  *
827  * @param domain_sid The domain sid acquired from the remote server
828  * @param cli A cli_state connected to the server.
829  * @param mem_ctx Talloc context, destoyed on completion of the function.
830  * @param argc  Standard main() style argc
831  * @param argv  Standard main() style argv.  Initial components are already
832  *              stripped
833  *
834  * @return Normal NTSTATUS return.
835  **/
836
837 static NTSTATUS 
838 rpc_user_info_internals(const DOM_SID *domain_sid, const char *domain_name, 
839                         struct cli_state *cli,
840                         TALLOC_CTX *mem_ctx, int argc, const char **argv)
841 {
842         POLICY_HND connect_pol, domain_pol, user_pol;
843         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
844         uint32 *rids, num_rids, *name_types, num_names;
845         uint32 flags = 0x000003e8; /* Unknown */
846         int i;
847         char **names;
848         DOM_GID *user_gids;
849
850         if (argc < 1) {
851                 d_printf("User must be specified\n");
852                 rpc_user_usage(argc, argv);
853                 return NT_STATUS_OK;
854         }
855         /* Get sam policy handle */
856         
857         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
858                                   &connect_pol);
859         if (!NT_STATUS_IS_OK(result)) goto done;
860         
861         /* Get domain policy handle */
862         
863         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
864                                       MAXIMUM_ALLOWED_ACCESS,
865                                       domain_sid, &domain_pol);
866         if (!NT_STATUS_IS_OK(result)) goto done;
867
868         /* Get handle on user */
869
870         result = cli_samr_lookup_names(cli, mem_ctx, &domain_pol,
871                                        flags, 1, &argv[0],
872                                        &num_rids, &rids, &name_types);
873
874         if (!NT_STATUS_IS_OK(result)) goto done;
875
876         result = cli_samr_open_user(cli, mem_ctx, &domain_pol,
877                                     MAXIMUM_ALLOWED_ACCESS,
878                                     rids[0], &user_pol);
879         if (!NT_STATUS_IS_OK(result)) goto done;
880
881         result = cli_samr_query_usergroups(cli, mem_ctx, &user_pol,
882                                            &num_rids, &user_gids);
883
884         /* Look up rids */
885
886         rids = (uint32 *)talloc(mem_ctx, sizeof(uint32) * num_rids);
887
888         for (i = 0; i < num_rids; i++)
889                 rids[i] = user_gids[i].g_rid;
890
891         result = cli_samr_lookup_rids(cli, mem_ctx, &domain_pol,
892                                       flags, num_rids, rids,
893                                       &num_names, &names, &name_types);
894
895         if (!NT_STATUS_IS_OK(result)) {
896                 goto done;
897         }
898
899         /* Display results */
900
901         for (i = 0; i < num_names; i++)
902                 printf("%s\n", names[i]);
903
904  done:
905         return result;
906 }
907
908 /** 
909  * List a user's groups from a remote RPC server
910  *
911  * @param argc  Standard main() style argc
912  * @param argv  Standard main() style argv.  Initial components are already
913  *              stripped
914  *
915  * @return A shell status integer (0 for success)
916  **/
917
918 static int rpc_user_info(int argc, const char **argv) 
919 {
920         return run_rpc_command(NULL, PI_SAMR, 0, rpc_user_info_internals,
921                                argc, argv);
922 }
923
924 /** 
925  * List users on a remote RPC server
926  *
927  * All parameters are provided by the run_rpc_command function, except for
928  * argc, argv which are passes through. 
929  *
930  * @param domain_sid The domain sid acquired from the remote server
931  * @param cli A cli_state connected to the server.
932  * @param mem_ctx Talloc context, destoyed on completion of the function.
933  * @param argc  Standard main() style argc
934  * @param argv  Standard main() style argv.  Initial components are already
935  *              stripped
936  *
937  * @return Normal NTSTATUS return.
938  **/
939
940 static NTSTATUS 
941 rpc_user_list_internals(const DOM_SID *domain_sid, const char *domain_name, 
942                         struct cli_state *cli,
943                         TALLOC_CTX *mem_ctx, int argc, const char **argv)
944 {
945         POLICY_HND connect_pol, domain_pol;
946         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
947         uint32 start_idx=0, num_entries, i, loop_count = 0;
948         SAM_DISPINFO_CTR ctr;
949         SAM_DISPINFO_1 info1;
950
951         /* Get sam policy handle */
952         
953         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
954                                   &connect_pol);
955         if (!NT_STATUS_IS_OK(result)) {
956                 goto done;
957         }
958         
959         /* Get domain policy handle */
960         
961         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
962                                       MAXIMUM_ALLOWED_ACCESS,
963                                       domain_sid, &domain_pol);
964         if (!NT_STATUS_IS_OK(result)) {
965                 goto done;
966         }
967
968         /* Query domain users */
969         ZERO_STRUCT(ctr);
970         ZERO_STRUCT(info1);
971         ctr.sam.info1 = &info1;
972         if (opt_long_list_entries)
973                 d_printf("\nUser name             Comment"\
974                          "\n-----------------------------\n");
975         do {
976                 fstring user, desc;
977                 uint32 max_entries, max_size;
978
979                 get_query_dispinfo_params(
980                         loop_count, &max_entries, &max_size);
981
982                 result = cli_samr_query_dispinfo(cli, mem_ctx, &domain_pol,
983                                                  &start_idx, 1, &num_entries,
984                                                  max_entries, max_size, &ctr);
985                 loop_count++;
986
987                 for (i = 0; i < num_entries; i++) {
988                         unistr2_to_ascii(user, &(&ctr.sam.info1->str[i])->uni_acct_name, sizeof(user)-1);
989                         if (opt_long_list_entries) 
990                                 unistr2_to_ascii(desc, &(&ctr.sam.info1->str[i])->uni_acct_desc, sizeof(desc)-1);
991                         
992                         if (opt_long_list_entries)
993                                 printf("%-21.21s %s\n", user, desc);
994                         else
995                                 printf("%s\n", user);
996                 }
997         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
998
999  done:
1000         return result;
1001 }
1002
1003 /** 
1004  * 'net rpc user' entrypoint.
1005  * @param argc  Standard main() style argc
1006  * @param argc  Standard main() style argv.  Initial components are already
1007  *              stripped
1008  **/
1009
1010 int net_rpc_user(int argc, const char **argv) 
1011 {
1012         struct functable func[] = {
1013                 {"add", rpc_user_add},
1014                 {"info", rpc_user_info},
1015                 {"delete", rpc_user_delete},
1016                 {"password", rpc_user_password},
1017                 {NULL, NULL}
1018         };
1019         
1020         if (argc == 0) {
1021                 if (opt_long_list_entries) {
1022                 } else {
1023                 }
1024                         return run_rpc_command(NULL,PI_SAMR, 0, 
1025                                                rpc_user_list_internals,
1026                                                argc, argv);
1027         }
1028
1029         return net_run_function(argc, argv, func, rpc_user_usage);
1030 }
1031
1032
1033 /****************************************************************************/
1034
1035 /**
1036  * Basic usage function for 'net rpc group'
1037  * @param argc  Standard main() style argc.
1038  * @param argv  Standard main() style argv.  Initial components are already
1039  *              stripped.
1040  **/
1041
1042 static int rpc_group_usage(int argc, const char **argv)
1043 {
1044         return net_help_group(argc, argv);
1045 }
1046
1047 /**
1048  * Delete group on a remote RPC server
1049  *
1050  * All parameters are provided by the run_rpc_command function, except for
1051  * argc, argv which are passes through.
1052  *
1053  * @param domain_sid The domain sid acquired from the remote server
1054  * @param cli A cli_state connected to the server.
1055  * @param mem_ctx Talloc context, destoyed on completion of the function.
1056  * @param argc  Standard main() style argc
1057  * @param argv  Standard main() style argv.  Initial components are already
1058  *              stripped
1059  *
1060  * @return Normal NTSTATUS return.
1061  **/
1062                                                                                                              
1063 static NTSTATUS rpc_group_delete_internals(const DOM_SID *domain_sid,
1064                                            const char *domain_name,
1065                                            struct cli_state *cli,
1066                                            TALLOC_CTX *mem_ctx,
1067                                            int argc, const char **argv)
1068 {
1069         POLICY_HND connect_pol, domain_pol, group_pol, user_pol;
1070         BOOL group_is_primary = False;
1071         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1072
1073         uint32 *group_rids, num_rids, *name_types, num_members, 
1074                *group_attrs, group_rid;
1075         uint32 flags = 0x000003e8; /* Unknown */
1076         /* char **names; */
1077         int i;
1078         /* DOM_GID *user_gids; */
1079         SAM_USERINFO_CTR *user_ctr;
1080         fstring temp;
1081
1082         if (argc < 1) {
1083                 d_printf("specify group\n");
1084                 rpc_group_usage(argc,argv);
1085                 return NT_STATUS_OK; /* ok? */
1086         }
1087
1088         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS,
1089                                   &connect_pol);
1090
1091         if (!NT_STATUS_IS_OK(result)) {
1092                 d_printf("Request samr_connect failed\n");
1093                 goto done;
1094         }
1095         
1096         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
1097                                       MAXIMUM_ALLOWED_ACCESS,
1098                                       domain_sid, &domain_pol);
1099         
1100         if (!NT_STATUS_IS_OK(result)) {
1101                 d_printf("Request open_domain failed\n");
1102                 goto done;
1103         }
1104         
1105         result = cli_samr_lookup_names(cli, mem_ctx, &domain_pol,
1106                                        flags, 1, &argv[0],
1107                                        &num_rids, &group_rids,
1108                                        &name_types);
1109
1110         if (!NT_STATUS_IS_OK(result)) {
1111                 d_printf("Lookup of '%s' failed\n",argv[0]);
1112                 goto done;
1113         }
1114
1115         switch (name_types[0])
1116         {
1117         case SID_NAME_DOM_GRP:
1118                 result = cli_samr_open_group(cli, mem_ctx, &domain_pol,
1119                                              MAXIMUM_ALLOWED_ACCESS,
1120                                              group_rids[0], &group_pol);
1121                 if (!NT_STATUS_IS_OK(result)) {
1122                         d_printf("Request open_group failed");
1123                         goto done;
1124                 }
1125                 
1126                 group_rid = group_rids[0];
1127                 
1128                 result = cli_samr_query_groupmem(cli, mem_ctx, &group_pol,
1129                                  &num_members, &group_rids,
1130                                  &group_attrs);
1131                 
1132                 if (!NT_STATUS_IS_OK(result)) {
1133                         d_printf("Unable to query group members of %s",argv[0]);
1134                         goto done;
1135                 }
1136                 
1137                 if (opt_verbose) {
1138                         d_printf("Domain Group %s (rid: %d) has %d members\n",
1139                                 argv[0],group_rid,num_members);
1140                 }
1141
1142                 /* Check if group is anyone's primary group */
1143                 for (i = 0; i < num_members; i++)
1144                 {
1145                         result = cli_samr_open_user(cli, mem_ctx, &domain_pol,
1146                                                     MAXIMUM_ALLOWED_ACCESS,
1147                                                     group_rids[i], &user_pol);
1148         
1149                         if (!NT_STATUS_IS_OK(result)) {
1150                                 d_printf("Unable to open group member %d\n",group_rids[i]);
1151                                 goto done;
1152                         }
1153         
1154                         ZERO_STRUCT(user_ctr);
1155
1156                         result = cli_samr_query_userinfo(cli, mem_ctx, &user_pol,
1157                                                          21, &user_ctr);
1158         
1159                         if (!NT_STATUS_IS_OK(result)) {
1160                                 d_printf("Unable to lookup userinfo for group member %d\n",group_rids[i]);
1161                                 goto done;
1162                         }
1163         
1164                         if (user_ctr->info.id21->group_rid == group_rid) {
1165                                 unistr2_to_ascii(temp, &(user_ctr->info.id21)->uni_user_name, 
1166                                                 sizeof(temp)-1);
1167                                 if (opt_verbose) 
1168                                         d_printf("Group is primary group of %s\n",temp);
1169                                 group_is_primary = True;
1170                         }
1171
1172                         cli_samr_close(cli, mem_ctx, &user_pol);
1173                 }
1174                 
1175                 if (group_is_primary) {
1176                         d_printf("Unable to delete group because some of it's "
1177                                  "members have it as primary group\n");
1178                         result = NT_STATUS_MEMBERS_PRIMARY_GROUP;
1179                         goto done;
1180                 }
1181      
1182                 /* remove all group members */
1183                 for (i = 0; i < num_members; i++)
1184                 {
1185                         if (opt_verbose) 
1186                                 d_printf("Remove group member %d...",group_rids[i]);
1187                         result = cli_samr_del_groupmem(cli, mem_ctx, &group_pol, group_rids[i]);
1188
1189                         if (NT_STATUS_IS_OK(result)) {
1190                                 if (opt_verbose)
1191                                         d_printf("ok\n");
1192                         } else {
1193                                 if (opt_verbose)
1194                                         d_printf("failed\n");
1195                                 goto done;
1196                         }       
1197                 }
1198
1199                 result = cli_samr_delete_dom_group(cli, mem_ctx, &group_pol);
1200
1201                 break;
1202         /* removing a local group is easier... */
1203         case SID_NAME_ALIAS:
1204                 result = cli_samr_open_alias(cli, mem_ctx, &domain_pol,
1205                                              MAXIMUM_ALLOWED_ACCESS,
1206                                              group_rids[0], &group_pol);
1207
1208                 if (!NT_STATUS_IS_OK(result)) {
1209                         d_printf("Request open_alias failed\n");
1210                         goto done;
1211                 }
1212                 
1213                 result = cli_samr_delete_dom_alias(cli, mem_ctx, &group_pol);
1214                 break;
1215         default:
1216                 d_printf("%s is of type %s. This command is only for deleting local or global groups\n",
1217                         argv[0],sid_type_lookup(name_types[0]));
1218                 result = NT_STATUS_UNSUCCESSFUL;
1219                 goto done;
1220         }
1221          
1222         
1223         if (NT_STATUS_IS_OK(result)) {
1224                 if (opt_verbose)
1225                         d_printf("Deleted %s '%s'\n",sid_type_lookup(name_types[0]),argv[0]);
1226         } else {
1227                 d_printf("Deleting of %s failed: %s\n",argv[0],
1228                         get_friendly_nt_error_msg(result));
1229         }
1230         
1231  done:
1232         return result;  
1233         
1234 }
1235
1236 static int rpc_group_delete(int argc, const char **argv)
1237 {
1238         return run_rpc_command(NULL, PI_SAMR, 0, rpc_group_delete_internals,
1239                                argc,argv);
1240 }
1241
1242 static NTSTATUS 
1243 rpc_group_add_internals(const DOM_SID *domain_sid, const char *domain_name, 
1244                         struct cli_state *cli,
1245                         TALLOC_CTX *mem_ctx, int argc, const char **argv)
1246 {
1247         POLICY_HND connect_pol, domain_pol, group_pol;
1248         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1249         GROUP_INFO_CTR group_info;
1250
1251         if (argc != 1) {
1252                 d_printf("Group name must be specified\n");
1253                 rpc_group_usage(argc, argv);
1254                 return NT_STATUS_OK;
1255         }
1256
1257         /* Get sam policy handle */
1258         
1259         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
1260                                   &connect_pol);
1261         if (!NT_STATUS_IS_OK(result)) goto done;
1262         
1263         /* Get domain policy handle */
1264         
1265         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
1266                                       MAXIMUM_ALLOWED_ACCESS,
1267                                       domain_sid, &domain_pol);
1268         if (!NT_STATUS_IS_OK(result)) goto done;
1269
1270         /* Create the group */
1271
1272         result = cli_samr_create_dom_group(cli, mem_ctx, &domain_pol,
1273                                            argv[0], MAXIMUM_ALLOWED_ACCESS,
1274                                            &group_pol);
1275         if (!NT_STATUS_IS_OK(result)) goto done;
1276
1277         if (strlen(opt_comment) == 0) goto done;
1278
1279         /* We've got a comment to set */
1280
1281         group_info.switch_value1 = 4;
1282         init_samr_group_info4(&group_info.group.info4, opt_comment);
1283
1284         result = cli_samr_set_groupinfo(cli, mem_ctx, &group_pol, &group_info);
1285         if (!NT_STATUS_IS_OK(result)) goto done;
1286         
1287  done:
1288         if (NT_STATUS_IS_OK(result))
1289                 DEBUG(5, ("add group succeeded\n"));
1290         else
1291                 d_printf("add group failed: %s\n", nt_errstr(result));
1292
1293         return result;
1294 }
1295
1296 static NTSTATUS 
1297 rpc_alias_add_internals(const DOM_SID *domain_sid, const char *domain_name, 
1298                         struct cli_state *cli,
1299                         TALLOC_CTX *mem_ctx, int argc, const char **argv)
1300 {
1301         POLICY_HND connect_pol, domain_pol, alias_pol;
1302         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1303         ALIAS_INFO_CTR alias_info;
1304
1305         if (argc != 1) {
1306                 d_printf("Group name must be specified\n");
1307                 rpc_group_usage(argc, argv);
1308                 return NT_STATUS_OK;
1309         }
1310
1311         /* Get sam policy handle */
1312         
1313         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
1314                                   &connect_pol);
1315         if (!NT_STATUS_IS_OK(result)) goto done;
1316         
1317         /* Get domain policy handle */
1318         
1319         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
1320                                       MAXIMUM_ALLOWED_ACCESS,
1321                                       domain_sid, &domain_pol);
1322         if (!NT_STATUS_IS_OK(result)) goto done;
1323
1324         /* Create the group */
1325
1326         result = cli_samr_create_dom_alias(cli, mem_ctx, &domain_pol,
1327                                            argv[0], &alias_pol);
1328         if (!NT_STATUS_IS_OK(result)) goto done;
1329
1330         if (strlen(opt_comment) == 0) goto done;
1331
1332         /* We've got a comment to set */
1333
1334         alias_info.switch_value1 = 3;
1335         alias_info.switch_value2 = 3;
1336         init_samr_alias_info3(&alias_info.alias.info3, opt_comment);
1337
1338         result = cli_samr_set_aliasinfo(cli, mem_ctx, &alias_pol, &alias_info);
1339         if (!NT_STATUS_IS_OK(result)) goto done;
1340         
1341  done:
1342         if (NT_STATUS_IS_OK(result))
1343                 DEBUG(5, ("add group succeeded\n"));
1344         else
1345                 d_printf("add group failed: %s\n", nt_errstr(result));
1346
1347         return result;
1348 }
1349
1350 static int rpc_group_add(int argc, const char **argv)
1351 {
1352         if (opt_localgroup)
1353                 return run_rpc_command(NULL, PI_SAMR, 0,
1354                                        rpc_alias_add_internals,
1355                                        argc, argv);
1356
1357         return run_rpc_command(NULL, PI_SAMR, 0,
1358                                rpc_group_add_internals,
1359                                argc, argv);
1360 }
1361
1362 static NTSTATUS
1363 get_sid_from_name(struct cli_state *cli, TALLOC_CTX *mem_ctx, const char *name,
1364                   DOM_SID *sid, enum SID_NAME_USE *type)
1365 {
1366         int current_pipe = cli->pipe_idx;
1367
1368         DOM_SID *sids = NULL;
1369         uint32 *types = NULL;
1370         POLICY_HND lsa_pol;
1371         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1372
1373         if (current_pipe != PI_LSARPC) {
1374
1375                 if (current_pipe != -1)
1376                         cli_nt_session_close(cli);
1377
1378                 if (!cli_nt_session_open(cli, PI_LSARPC))
1379                         goto done;
1380         }
1381
1382         result = cli_lsa_open_policy(cli, mem_ctx, False,
1383                                      SEC_RIGHTS_MAXIMUM_ALLOWED, &lsa_pol);
1384
1385         if (!NT_STATUS_IS_OK(result))
1386                 goto done;
1387
1388         result = cli_lsa_lookup_names(cli, mem_ctx, &lsa_pol, 1,
1389                                       &name, &sids, &types);
1390
1391         if (NT_STATUS_IS_OK(result)) {
1392                 sid_copy(sid, &sids[0]);
1393                 *type = types[0];
1394         }
1395
1396         cli_lsa_close(cli, mem_ctx, &lsa_pol);
1397
1398  done:
1399         if (current_pipe != PI_LSARPC) {
1400                 cli_nt_session_close(cli);
1401                 if (current_pipe != -1)
1402                         cli_nt_session_open(cli, current_pipe);
1403         }
1404
1405         if (!NT_STATUS_IS_OK(result) && (StrnCaseCmp(name, "S-", 2) == 0)) {
1406
1407                 /* Try as S-1-5-whatever */
1408
1409                 DOM_SID tmp_sid;
1410
1411                 if (string_to_sid(&tmp_sid, name)) {
1412                         sid_copy(sid, &tmp_sid);
1413                         *type = SID_NAME_UNKNOWN;
1414                         result = NT_STATUS_OK;
1415                 }
1416         }
1417
1418         return result;
1419 }
1420
1421 static NTSTATUS
1422 rpc_add_groupmem(struct cli_state *cli, TALLOC_CTX *mem_ctx,
1423                  const DOM_SID *group_sid, const char *member)
1424 {
1425         POLICY_HND connect_pol, domain_pol;
1426         NTSTATUS result;
1427         uint32 group_rid;
1428         POLICY_HND group_pol;
1429
1430         uint32 num_rids;
1431         uint32 *rids = NULL;
1432         uint32 *rid_types = NULL;
1433
1434         DOM_SID sid;
1435
1436         sid_copy(&sid, group_sid);
1437
1438         if (!sid_split_rid(&sid, &group_rid))
1439                 return NT_STATUS_UNSUCCESSFUL;
1440
1441         /* Get sam policy handle */     
1442         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
1443                                   &connect_pol);
1444         if (!NT_STATUS_IS_OK(result))
1445                 return result;
1446         
1447         /* Get domain policy handle */
1448         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
1449                                       MAXIMUM_ALLOWED_ACCESS,
1450                                       &sid, &domain_pol);
1451         if (!NT_STATUS_IS_OK(result))
1452                 return result;
1453
1454         result = cli_samr_lookup_names(cli, mem_ctx, &domain_pol, 1000,
1455                                        1, &member,
1456                                        &num_rids, &rids, &rid_types);
1457
1458         if (!NT_STATUS_IS_OK(result)) {
1459                 d_printf("Could not lookup up group member %s\n", member);
1460                 goto done;
1461         }
1462
1463         result = cli_samr_open_group(cli, mem_ctx, &domain_pol,
1464                                      MAXIMUM_ALLOWED_ACCESS,
1465                                      group_rid, &group_pol);
1466
1467         if (!NT_STATUS_IS_OK(result))
1468                 goto done;
1469
1470         result = cli_samr_add_groupmem(cli, mem_ctx, &group_pol, rids[0]);
1471
1472  done:
1473         cli_samr_close(cli, mem_ctx, &connect_pol);
1474         return result;
1475 }
1476
1477 static NTSTATUS
1478 rpc_add_aliasmem(struct cli_state *cli, TALLOC_CTX *mem_ctx,
1479                  const DOM_SID *alias_sid, const char *member)
1480 {
1481         POLICY_HND connect_pol, domain_pol;
1482         NTSTATUS result;
1483         uint32 alias_rid;
1484         POLICY_HND alias_pol;
1485
1486         DOM_SID member_sid;
1487         enum SID_NAME_USE member_type;
1488
1489         DOM_SID sid;
1490
1491         sid_copy(&sid, alias_sid);
1492
1493         if (!sid_split_rid(&sid, &alias_rid))
1494                 return NT_STATUS_UNSUCCESSFUL;
1495
1496         result = get_sid_from_name(cli, mem_ctx, member,
1497                                    &member_sid, &member_type);
1498
1499         if (!NT_STATUS_IS_OK(result)) {
1500                 d_printf("Could not lookup up group member %s\n", member);
1501                 return result;
1502         }
1503
1504         /* Get sam policy handle */     
1505         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
1506                                   &connect_pol);
1507         if (!NT_STATUS_IS_OK(result)) {
1508                 goto done;
1509         }
1510         
1511         /* Get domain policy handle */
1512         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
1513                                       MAXIMUM_ALLOWED_ACCESS,
1514                                       &sid, &domain_pol);
1515         if (!NT_STATUS_IS_OK(result)) {
1516                 goto done;
1517         }
1518
1519         result = cli_samr_open_alias(cli, mem_ctx, &domain_pol,
1520                                      MAXIMUM_ALLOWED_ACCESS,
1521                                      alias_rid, &alias_pol);
1522
1523         if (!NT_STATUS_IS_OK(result))
1524                 return result;
1525
1526         result = cli_samr_add_aliasmem(cli, mem_ctx, &alias_pol, &member_sid);
1527
1528         if (!NT_STATUS_IS_OK(result))
1529                 return result;
1530
1531  done:
1532         cli_samr_close(cli, mem_ctx, &connect_pol);
1533         return result;
1534 }
1535
1536 static NTSTATUS 
1537 rpc_group_addmem_internals(const DOM_SID *domain_sid, const char *domain_name, 
1538                            struct cli_state *cli,
1539                            TALLOC_CTX *mem_ctx, int argc, const char **argv)
1540 {
1541         DOM_SID group_sid;
1542         enum SID_NAME_USE group_type;
1543
1544         if (argc != 2) {
1545                 d_printf("Usage: 'net rpc group addmem <group> <member>\n");
1546                 return NT_STATUS_UNSUCCESSFUL;
1547         }
1548
1549         if (!NT_STATUS_IS_OK(get_sid_from_name(cli, mem_ctx, argv[0],
1550                                                &group_sid, &group_type))) {
1551                 d_printf("Could not lookup group name %s\n", argv[0]);
1552                 return NT_STATUS_UNSUCCESSFUL;
1553         }
1554
1555         if (group_type == SID_NAME_DOM_GRP) {
1556                 NTSTATUS result = rpc_add_groupmem(cli, mem_ctx,
1557                                                    &group_sid, argv[1]);
1558
1559                 if (!NT_STATUS_IS_OK(result)) {
1560                         d_printf("Could not add %s to %s: %s\n",
1561                                  argv[1], argv[0], nt_errstr(result));
1562                 }
1563                 return result;
1564         }
1565
1566         if (group_type == SID_NAME_ALIAS) {
1567                 NTSTATUS result = rpc_add_aliasmem(cli, mem_ctx,
1568                                                    &group_sid, argv[1]);
1569
1570                 if (!NT_STATUS_IS_OK(result)) {
1571                         d_printf("Could not add %s to %s: %s\n",
1572                                  argv[1], argv[0], nt_errstr(result));
1573                 }
1574                 return result;
1575         }
1576
1577         d_printf("Can only add members to global or local groups which "
1578                  "%s is not\n", argv[0]);
1579
1580         return NT_STATUS_UNSUCCESSFUL;
1581 }
1582
1583 static int rpc_group_addmem(int argc, const char **argv)
1584 {
1585         return run_rpc_command(NULL, PI_SAMR, 0,
1586                                rpc_group_addmem_internals,
1587                                argc, argv);
1588 }
1589
1590 static NTSTATUS
1591 rpc_del_groupmem(struct cli_state *cli, TALLOC_CTX *mem_ctx,
1592                  const DOM_SID *group_sid, const char *member)
1593 {
1594         POLICY_HND connect_pol, domain_pol;
1595         NTSTATUS result;
1596         uint32 group_rid;
1597         POLICY_HND group_pol;
1598
1599         uint32 num_rids;
1600         uint32 *rids = NULL;
1601         uint32 *rid_types = NULL;
1602
1603         DOM_SID sid;
1604
1605         sid_copy(&sid, group_sid);
1606
1607         if (!sid_split_rid(&sid, &group_rid))
1608                 return NT_STATUS_UNSUCCESSFUL;
1609
1610         /* Get sam policy handle */     
1611         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
1612                                   &connect_pol);
1613         if (!NT_STATUS_IS_OK(result))
1614                 return result;
1615         
1616         /* Get domain policy handle */
1617         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
1618                                       MAXIMUM_ALLOWED_ACCESS,
1619                                       &sid, &domain_pol);
1620         if (!NT_STATUS_IS_OK(result))
1621                 return result;
1622
1623         result = cli_samr_lookup_names(cli, mem_ctx, &domain_pol, 1000,
1624                                        1, &member,
1625                                        &num_rids, &rids, &rid_types);
1626
1627         if (!NT_STATUS_IS_OK(result)) {
1628                 d_printf("Could not lookup up group member %s\n", member);
1629                 goto done;
1630         }
1631
1632         result = cli_samr_open_group(cli, mem_ctx, &domain_pol,
1633                                      MAXIMUM_ALLOWED_ACCESS,
1634                                      group_rid, &group_pol);
1635
1636         if (!NT_STATUS_IS_OK(result))
1637                 goto done;
1638
1639         result = cli_samr_del_groupmem(cli, mem_ctx, &group_pol, rids[0]);
1640
1641  done:
1642         cli_samr_close(cli, mem_ctx, &connect_pol);
1643         return result;
1644 }
1645
1646 static NTSTATUS
1647 rpc_del_aliasmem(struct cli_state *cli, TALLOC_CTX *mem_ctx,
1648                  const DOM_SID *alias_sid, const char *member)
1649 {
1650         POLICY_HND connect_pol, domain_pol;
1651         NTSTATUS result;
1652         uint32 alias_rid;
1653         POLICY_HND alias_pol;
1654
1655         DOM_SID member_sid;
1656         enum SID_NAME_USE member_type;
1657
1658         DOM_SID sid;
1659
1660         sid_copy(&sid, alias_sid);
1661
1662         if (!sid_split_rid(&sid, &alias_rid))
1663                 return NT_STATUS_UNSUCCESSFUL;
1664
1665         result = get_sid_from_name(cli, mem_ctx, member,
1666                                    &member_sid, &member_type);
1667
1668         if (!NT_STATUS_IS_OK(result)) {
1669                 d_printf("Could not lookup up group member %s\n", member);
1670                 return result;
1671         }
1672
1673         /* Get sam policy handle */     
1674         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
1675                                   &connect_pol);
1676         if (!NT_STATUS_IS_OK(result)) {
1677                 goto done;
1678         }
1679         
1680         /* Get domain policy handle */
1681         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
1682                                       MAXIMUM_ALLOWED_ACCESS,
1683                                       &sid, &domain_pol);
1684         if (!NT_STATUS_IS_OK(result)) {
1685                 goto done;
1686         }
1687
1688         result = cli_samr_open_alias(cli, mem_ctx, &domain_pol,
1689                                      MAXIMUM_ALLOWED_ACCESS,
1690                                      alias_rid, &alias_pol);
1691
1692         if (!NT_STATUS_IS_OK(result))
1693                 return result;
1694
1695         result = cli_samr_del_aliasmem(cli, mem_ctx, &alias_pol, &member_sid);
1696
1697         if (!NT_STATUS_IS_OK(result))
1698                 return result;
1699
1700  done:
1701         cli_samr_close(cli, mem_ctx, &connect_pol);
1702         return result;
1703 }
1704
1705 static NTSTATUS 
1706 rpc_group_delmem_internals(const DOM_SID *domain_sid, const char *domain_name, 
1707                            struct cli_state *cli,
1708                            TALLOC_CTX *mem_ctx, int argc, const char **argv)
1709 {
1710         DOM_SID group_sid;
1711         enum SID_NAME_USE group_type;
1712
1713         if (argc != 2) {
1714                 d_printf("Usage: 'net rpc group delmem <group> <member>\n");
1715                 return NT_STATUS_UNSUCCESSFUL;
1716         }
1717
1718         if (!NT_STATUS_IS_OK(get_sid_from_name(cli, mem_ctx, argv[0],
1719                                                &group_sid, &group_type))) {
1720                 d_printf("Could not lookup group name %s\n", argv[0]);
1721                 return NT_STATUS_UNSUCCESSFUL;
1722         }
1723
1724         if (group_type == SID_NAME_DOM_GRP) {
1725                 NTSTATUS result = rpc_del_groupmem(cli, mem_ctx,
1726                                                    &group_sid, argv[1]);
1727
1728                 if (!NT_STATUS_IS_OK(result)) {
1729                         d_printf("Could not del %s from %s: %s\n",
1730                                  argv[1], argv[0], nt_errstr(result));
1731                 }
1732                 return result;
1733         }
1734
1735         if (group_type == SID_NAME_ALIAS) {
1736                 NTSTATUS result = rpc_del_aliasmem(cli, mem_ctx, 
1737                                                    &group_sid, argv[1]);
1738
1739                 if (!NT_STATUS_IS_OK(result)) {
1740                         d_printf("Could not del %s from %s: %s\n",
1741                                  argv[1], argv[0], nt_errstr(result));
1742                 }
1743                 return result;
1744         }
1745
1746         d_printf("Can only delete members from global or local groups which "
1747                  "%s is not\n", argv[0]);
1748
1749         return NT_STATUS_UNSUCCESSFUL;
1750 }
1751
1752 static int rpc_group_delmem(int argc, const char **argv)
1753 {
1754         return run_rpc_command(NULL, PI_SAMR, 0,
1755                                rpc_group_delmem_internals,
1756                                argc, argv);
1757 }
1758
1759 /** 
1760  * List groups on a remote RPC server
1761  *
1762  * All parameters are provided by the run_rpc_command function, except for
1763  * argc, argv which are passes through. 
1764  *
1765  * @param domain_sid The domain sid acquired from the remote server
1766  * @param cli A cli_state connected to the server.
1767  * @param mem_ctx Talloc context, destoyed on completion of the function.
1768  * @param argc  Standard main() style argc
1769  * @param argv  Standard main() style argv.  Initial components are already
1770  *              stripped
1771  *
1772  * @return Normal NTSTATUS return.
1773  **/
1774
1775 static NTSTATUS 
1776 rpc_group_list_internals(const DOM_SID *domain_sid, const char *domain_name, 
1777                          struct cli_state *cli,
1778                          TALLOC_CTX *mem_ctx, int argc, const char **argv)
1779 {
1780         POLICY_HND connect_pol, domain_pol;
1781         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1782         uint32 start_idx=0, max_entries=250, num_entries, i, loop_count = 0;
1783         struct acct_info *groups;
1784         DOM_SID global_sid_Builtin;
1785         BOOL global = False;
1786         BOOL local = False;
1787         BOOL builtin = False;
1788
1789         if (argc == 0) {
1790                 global = True;
1791                 local = True;
1792                 builtin = True;
1793         }
1794
1795         for (i=0; i<argc; i++) {
1796                 if (strequal(argv[i], "global"))
1797                         global = True;
1798
1799                 if (strequal(argv[i], "local"))
1800                         local = True;
1801
1802                 if (strequal(argv[i], "builtin"))
1803                         builtin = True;
1804         }
1805
1806         string_to_sid(&global_sid_Builtin, "S-1-5-32");
1807
1808         /* Get sam policy handle */
1809         
1810         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
1811                                   &connect_pol);
1812         if (!NT_STATUS_IS_OK(result)) {
1813                 goto done;
1814         }
1815         
1816         /* Get domain policy handle */
1817         
1818         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
1819                                       MAXIMUM_ALLOWED_ACCESS,
1820                                       domain_sid, &domain_pol);
1821         if (!NT_STATUS_IS_OK(result)) {
1822                 goto done;
1823         }
1824
1825         /* Query domain groups */
1826         if (opt_long_list_entries)
1827                 d_printf("\nGroup name            Comment"\
1828                          "\n-----------------------------\n");
1829         do {
1830                 SAM_DISPINFO_CTR ctr;
1831                 SAM_DISPINFO_3 info3;
1832                 uint32 max_size;
1833
1834                 ZERO_STRUCT(ctr);
1835                 ZERO_STRUCT(info3);
1836                 ctr.sam.info3 = &info3;
1837
1838                 if (!global) break;
1839
1840                 get_query_dispinfo_params(
1841                         loop_count, &max_entries, &max_size);
1842
1843                 result = cli_samr_query_dispinfo(cli, mem_ctx, &domain_pol,
1844                                                  &start_idx, 3, &num_entries,
1845                                                  max_entries, max_size, &ctr);
1846
1847                 if (!NT_STATUS_IS_OK(result) &&
1848                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
1849                         break;
1850                                                  
1851                 for (i = 0; i < num_entries; i++) {
1852
1853                         fstring group, desc;
1854
1855                         unistr2_to_ascii(group, &(&ctr.sam.info3->str[i])->uni_grp_name, sizeof(group)-1);
1856                         unistr2_to_ascii(desc, &(&ctr.sam.info3->str[i])->uni_grp_desc, sizeof(desc)-1);
1857                         
1858                         if (opt_long_list_entries)
1859                                 printf("%-21.21s %-50.50s\n",
1860                                        group, desc);
1861                         else
1862                                 printf("%s\n", group);
1863                 }
1864         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1865         /* query domain aliases */
1866         start_idx = 0;
1867         do {
1868                 if (!local) break;
1869
1870                 /* The max_size field in cli_samr_enum_als_groups is more like
1871                  * an account_control field with indiviual bits what to
1872                  * retrieve. Set this to 0xffff as NT4 usrmgr.exe does to get
1873                  * everything. I'm too lazy (sorry) to get this through to
1874                  * rpc_parse/ etc.  Volker */
1875
1876                 result = cli_samr_enum_als_groups(cli, mem_ctx, &domain_pol,
1877                                                   &start_idx, 0xffff,
1878                                                   &groups, &num_entries);
1879
1880                 if (!NT_STATUS_IS_OK(result) &&
1881                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
1882                         break;
1883                                                  
1884                 for (i = 0; i < num_entries; i++) {
1885
1886                         char *description = NULL;
1887
1888                         if (opt_long_list_entries) {
1889
1890                                 POLICY_HND alias_pol;
1891                                 ALIAS_INFO_CTR ctr;
1892
1893                                 if ((NT_STATUS_IS_OK(cli_samr_open_alias(cli, mem_ctx,
1894                                                                          &domain_pol,
1895                                                                          0x8,
1896                                                                          groups[i].rid,
1897                                                                          &alias_pol))) &&
1898                                     (NT_STATUS_IS_OK(cli_samr_query_alias_info(cli, mem_ctx,
1899                                                                                &alias_pol, 3,
1900                                                                                &ctr))) &&
1901                                     (NT_STATUS_IS_OK(cli_samr_close(cli, mem_ctx,
1902                                                                     &alias_pol)))) {
1903                                         description = unistr2_tdup(mem_ctx,
1904                                                                    &ctr.alias.info3.uni_acct_desc);
1905                                 }
1906                         }
1907                         
1908                         if (description != NULL) {
1909                                 printf("%-21.21s %-50.50s\n", 
1910                                        groups[i].acct_name,
1911                                        description);
1912                         } else {
1913                                 printf("%s\n", groups[i].acct_name);
1914                         }
1915                 }
1916         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1917         cli_samr_close(cli, mem_ctx, &domain_pol);
1918         /* Get builtin policy handle */
1919         
1920         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
1921                                       MAXIMUM_ALLOWED_ACCESS,
1922                                       &global_sid_Builtin, &domain_pol);
1923         if (!NT_STATUS_IS_OK(result)) {
1924                 goto done;
1925         }
1926         /* query builtin aliases */
1927         start_idx = 0;
1928         do {
1929                 if (!builtin) break;
1930
1931                 result = cli_samr_enum_als_groups(cli, mem_ctx, &domain_pol,
1932                                                   &start_idx, max_entries,
1933                                                   &groups, &num_entries);
1934                                                  
1935                 if (!NT_STATUS_IS_OK(result) &&
1936                     !NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES))
1937                         break;
1938                                                  
1939                 for (i = 0; i < num_entries; i++) {
1940
1941                         char *description = NULL;
1942
1943                         if (opt_long_list_entries) {
1944
1945                                 POLICY_HND alias_pol;
1946                                 ALIAS_INFO_CTR ctr;
1947
1948                                 if ((NT_STATUS_IS_OK(cli_samr_open_alias(cli, mem_ctx,
1949                                                                          &domain_pol,
1950                                                                          0x8,
1951                                                                          groups[i].rid,
1952                                                                          &alias_pol))) &&
1953                                     (NT_STATUS_IS_OK(cli_samr_query_alias_info(cli, mem_ctx,
1954                                                                                &alias_pol, 3,
1955                                                                                &ctr))) &&
1956                                     (NT_STATUS_IS_OK(cli_samr_close(cli, mem_ctx,
1957                                                                     &alias_pol)))) {
1958                                         description = unistr2_tdup(mem_ctx,
1959                                                                    &ctr.alias.info3.uni_acct_desc);
1960                                 }
1961                         }
1962                         
1963                         if (description != NULL) {
1964                                 printf("%-21.21s %-50.50s\n", 
1965                                        groups[i].acct_name,
1966                                        description);
1967                         } else {
1968                                 printf("%s\n", groups[i].acct_name);
1969                         }
1970                 }
1971         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
1972
1973  done:
1974         return result;
1975 }
1976
1977 static int rpc_group_list(int argc, const char **argv)
1978 {
1979         return run_rpc_command(NULL, PI_SAMR, 0,
1980                                rpc_group_list_internals,
1981                                argc, argv);
1982 }
1983
1984 static NTSTATUS
1985 rpc_list_group_members(struct cli_state *cli, TALLOC_CTX *mem_ctx,
1986                        const char *domain_name, const DOM_SID *domain_sid,
1987                        POLICY_HND *domain_pol, uint32 rid)
1988 {
1989         NTSTATUS result;
1990         POLICY_HND group_pol;
1991         uint32 num_members, *group_rids, *group_attrs;
1992         uint32 num_names;
1993         char **names;
1994         uint32 *name_types;
1995         int i;
1996
1997         fstring sid_str;
1998         sid_to_string(sid_str, domain_sid);
1999
2000         result = cli_samr_open_group(cli, mem_ctx, domain_pol,
2001                                      MAXIMUM_ALLOWED_ACCESS,
2002                                      rid, &group_pol);
2003
2004         if (!NT_STATUS_IS_OK(result))
2005                 return result;
2006
2007         result = cli_samr_query_groupmem(cli, mem_ctx, &group_pol,
2008                                          &num_members, &group_rids,
2009                                          &group_attrs);
2010
2011         if (!NT_STATUS_IS_OK(result))
2012                 return result;
2013
2014         while (num_members > 0) {
2015                 int this_time = 512;
2016
2017                 if (num_members < this_time)
2018                         this_time = num_members;
2019
2020                 result = cli_samr_lookup_rids(cli, mem_ctx, domain_pol, 1000,
2021                                               this_time, group_rids,
2022                                               &num_names, &names, &name_types);
2023
2024                 if (!NT_STATUS_IS_OK(result))
2025                         return result;
2026
2027                 /* We only have users as members, but make the output
2028                    the same as the output of alias members */
2029
2030                 for (i = 0; i < this_time; i++) {
2031
2032                         if (opt_long_list_entries) {
2033                                 printf("%s-%d %s\\%s %d\n", sid_str,
2034                                        group_rids[i], domain_name, names[i],
2035                                        SID_NAME_USER);
2036                         } else {
2037                                 printf("%s\\%s\n", domain_name, names[i]);
2038                         }
2039                 }
2040
2041                 num_members -= this_time;
2042                 group_rids += 512;
2043         }
2044
2045         return NT_STATUS_OK;
2046 }
2047
2048 static NTSTATUS
2049 rpc_list_alias_members(struct cli_state *cli, TALLOC_CTX *mem_ctx,
2050                        POLICY_HND *domain_pol, uint32 rid)
2051 {
2052         NTSTATUS result;
2053         POLICY_HND alias_pol, lsa_pol;
2054         uint32 num_members;
2055         DOM_SID *alias_sids;
2056         char **domains;
2057         char **names;
2058         uint32 *types;
2059         int i;
2060
2061         result = cli_samr_open_alias(cli, mem_ctx, domain_pol,
2062                                      MAXIMUM_ALLOWED_ACCESS, rid, &alias_pol);
2063
2064         if (!NT_STATUS_IS_OK(result))
2065                 return result;
2066
2067         result = cli_samr_query_aliasmem(cli, mem_ctx, &alias_pol,
2068                                          &num_members, &alias_sids);
2069
2070         if (!NT_STATUS_IS_OK(result)) {
2071                 d_printf("Couldn't list alias members\n");
2072                 return result;
2073         }
2074
2075         if (num_members == 0) {
2076                 return NT_STATUS_OK;
2077         }
2078
2079         cli_nt_session_close(cli);
2080
2081         if (!cli_nt_session_open(cli, PI_LSARPC)) {
2082                 d_printf("Couldn't open LSA pipe\n");
2083                 return result;
2084         }
2085
2086         result = cli_lsa_open_policy(cli, mem_ctx, True,
2087                                      SEC_RIGHTS_MAXIMUM_ALLOWED, &lsa_pol);
2088
2089         if (!NT_STATUS_IS_OK(result)) {
2090                 d_printf("Couldn't open LSA policy handle\n");
2091                 return result;
2092         }
2093
2094         result = cli_lsa_lookup_sids(cli, mem_ctx, &lsa_pol, num_members,
2095                                      alias_sids, 
2096                                      &domains, &names, &types);
2097
2098         if (!NT_STATUS_IS_OK(result) &&
2099             !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED)) {
2100                 d_printf("Couldn't lookup SIDs\n");
2101                 return result;
2102         }
2103
2104         for (i = 0; i < num_members; i++) {
2105                 fstring sid_str;
2106                 sid_to_string(sid_str, &alias_sids[i]);
2107
2108                 if (opt_long_list_entries) {
2109                         printf("%s %s\\%s %d\n", sid_str, 
2110                                domains[i] ? domains[i] : "*unknown*", 
2111                                names[i] ? names[i] : "*unknown*", types[i]);
2112                 } else {
2113                         if (domains[i])
2114                                 printf("%s\\%s\n", domains[i], names[i]);
2115                         else
2116                                 printf("%s\n", sid_str);
2117                 }
2118         }
2119
2120         return NT_STATUS_OK;
2121 }
2122  
2123 static NTSTATUS 
2124 rpc_group_members_internals(const DOM_SID *domain_sid,
2125                             const char *domain_name, 
2126                             struct cli_state *cli,
2127                             TALLOC_CTX *mem_ctx, int argc, const char **argv)
2128 {
2129         NTSTATUS result;
2130         POLICY_HND connect_pol, domain_pol;
2131         uint32 num_rids, *rids, *rid_types;
2132
2133         /* Get sam policy handle */
2134         
2135         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
2136                                   &connect_pol);
2137
2138         if (!NT_STATUS_IS_OK(result))
2139                 return result;
2140         
2141         /* Get domain policy handle */
2142         
2143         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
2144                                       MAXIMUM_ALLOWED_ACCESS,
2145                                       domain_sid, &domain_pol);
2146
2147         if (!NT_STATUS_IS_OK(result))
2148                 return result;
2149
2150         result = cli_samr_lookup_names(cli, mem_ctx, &domain_pol, 1000,
2151                                        1, argv, &num_rids, &rids, &rid_types);
2152
2153         if (!NT_STATUS_IS_OK(result)) {
2154
2155                 /* Ok, did not find it in the global sam, try with builtin */
2156
2157                 DOM_SID sid_Builtin;
2158
2159                 cli_samr_close(cli, mem_ctx, &domain_pol);
2160
2161                 string_to_sid(&sid_Builtin, "S-1-5-32");                
2162
2163                 result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
2164                                               MAXIMUM_ALLOWED_ACCESS,
2165                                               &sid_Builtin, &domain_pol);
2166
2167                 if (!NT_STATUS_IS_OK(result)) {
2168                         d_printf("Couldn't find group %s\n", argv[0]);
2169                         return result;
2170                 }
2171
2172                 result = cli_samr_lookup_names(cli, mem_ctx, &domain_pol, 1000,
2173                                                1, argv, &num_rids,
2174                                                &rids, &rid_types);
2175
2176                 if (!NT_STATUS_IS_OK(result)) {
2177                         d_printf("Couldn't find group %s\n", argv[0]);
2178                         return result;
2179                 }
2180         }
2181
2182         if (num_rids != 1) {
2183                 d_printf("Couldn't find group %s\n", argv[0]);
2184                 return result;
2185         }
2186
2187         if (rid_types[0] == SID_NAME_DOM_GRP) {
2188                 return rpc_list_group_members(cli, mem_ctx, domain_name,
2189                                               domain_sid, &domain_pol,
2190                                               rids[0]);
2191         }
2192
2193         if (rid_types[0] == SID_NAME_ALIAS) {
2194                 return rpc_list_alias_members(cli, mem_ctx, &domain_pol,
2195                                               rids[0]);
2196         }
2197
2198         return NT_STATUS_NO_SUCH_GROUP;
2199 }
2200
2201 static int rpc_group_members(int argc, const char **argv)
2202 {
2203         if (argc != 1) {
2204                 return rpc_group_usage(argc, argv);
2205         }
2206
2207         return run_rpc_command(NULL, PI_SAMR, 0,
2208                                rpc_group_members_internals,
2209                                argc, argv);
2210 }
2211
2212 static NTSTATUS 
2213 rpc_group_rename_internals(const DOM_SID *domain_sid,
2214                             const char *domain_name, 
2215                             struct cli_state *cli,
2216                             TALLOC_CTX *mem_ctx, int argc, const char **argv)
2217 {
2218         NTSTATUS result;
2219         POLICY_HND connect_pol, domain_pol, group_pol;
2220         uint32 num_rids, *rids, *rid_types;
2221         GROUP_INFO_CTR ctr;
2222
2223         if (argc != 2) {
2224                 d_printf("Usage: 'net rpc group rename group newname'\n");
2225                 return NT_STATUS_UNSUCCESSFUL;
2226         }
2227
2228         /* Get sam policy handle */
2229         
2230         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
2231                                   &connect_pol);
2232
2233         if (!NT_STATUS_IS_OK(result))
2234                 return result;
2235         
2236         /* Get domain policy handle */
2237         
2238         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
2239                                       MAXIMUM_ALLOWED_ACCESS,
2240                                       domain_sid, &domain_pol);
2241
2242         if (!NT_STATUS_IS_OK(result))
2243                 return result;
2244
2245         result = cli_samr_lookup_names(cli, mem_ctx, &domain_pol, 1000,
2246                                        1, argv, &num_rids, &rids, &rid_types);
2247
2248         if (num_rids != 1) {
2249                 d_printf("Couldn't find group %s\n", argv[0]);
2250                 return result;
2251         }
2252
2253         if (rid_types[0] != SID_NAME_DOM_GRP) {
2254                 d_printf("Can only rename domain groups\n");
2255                 return NT_STATUS_UNSUCCESSFUL;
2256         }
2257
2258         result = cli_samr_open_group(cli, mem_ctx, &domain_pol,
2259                                      MAXIMUM_ALLOWED_ACCESS,
2260                                      rids[0], &group_pol);
2261
2262         if (!NT_STATUS_IS_OK(result))
2263                 return result;
2264
2265         ZERO_STRUCT(ctr);
2266
2267         ctr.switch_value1 = 2;
2268         init_samr_group_info2(&ctr.group.info2, argv[1]);
2269
2270         result = cli_samr_set_groupinfo(cli, mem_ctx, &group_pol, &ctr);
2271
2272         if (!NT_STATUS_IS_OK(result))
2273                 return result;
2274
2275         return NT_STATUS_NO_SUCH_GROUP;
2276 }
2277
2278 static int rpc_group_rename(int argc, const char **argv)
2279 {
2280         if (argc != 2) {
2281                 return rpc_group_usage(argc, argv);
2282         }
2283
2284         return run_rpc_command(NULL, PI_SAMR, 0,
2285                                rpc_group_rename_internals,
2286                                argc, argv);
2287 }
2288
2289 /** 
2290  * 'net rpc group' entrypoint.
2291  * @param argc  Standard main() style argc
2292  * @param argc  Standard main() style argv.  Initial components are already
2293  *              stripped
2294  **/
2295
2296 int net_rpc_group(int argc, const char **argv) 
2297 {
2298         struct functable func[] = {
2299                 {"add", rpc_group_add},
2300                 {"delete", rpc_group_delete},
2301                 {"addmem", rpc_group_addmem},
2302                 {"delmem", rpc_group_delmem},
2303                 {"list", rpc_group_list},
2304                 {"members", rpc_group_members},
2305                 {"rename", rpc_group_rename},
2306                 {NULL, NULL}
2307         };
2308         
2309         if (argc == 0) {
2310                 if (opt_long_list_entries) {
2311                 } else {
2312                 }
2313                 return run_rpc_command(NULL, PI_SAMR, 0, 
2314                                        rpc_group_list_internals,
2315                                        argc, argv);
2316         }
2317
2318         return net_run_function(argc, argv, func, rpc_group_usage);
2319 }
2320
2321 /****************************************************************************/
2322
2323 static int rpc_share_usage(int argc, const char **argv)
2324 {
2325         return net_help_share(argc, argv);
2326 }
2327
2328 /** 
2329  * Add a share on a remote RPC server
2330  *
2331  * All parameters are provided by the run_rpc_command function, except for
2332  * argc, argv which are passes through. 
2333  *
2334  * @param domain_sid The domain sid acquired from the remote server
2335  * @param cli A cli_state connected to the server.
2336  * @param mem_ctx Talloc context, destoyed on completion of the function.
2337  * @param argc  Standard main() style argc
2338  * @param argv  Standard main() style argv.  Initial components are already
2339  *              stripped
2340  *
2341  * @return Normal NTSTATUS return.
2342  **/
2343 static NTSTATUS 
2344 rpc_share_add_internals(const DOM_SID *domain_sid, const char *domain_name, 
2345                         struct cli_state *cli,
2346                         TALLOC_CTX *mem_ctx,int argc, const char **argv)
2347 {
2348         WERROR result;
2349         char *sharename=talloc_strdup(mem_ctx, argv[0]);
2350         char *path;
2351         uint32 type=0; /* only allow disk shares to be added */
2352         uint32 num_users=0, perms=0;
2353         char *password=NULL; /* don't allow a share password */
2354         uint32 level = 2;
2355
2356         path = strchr(sharename, '=');
2357         if (!path)
2358                 return NT_STATUS_UNSUCCESSFUL;
2359         *path++ = '\0';
2360
2361         result = cli_srvsvc_net_share_add(cli, mem_ctx, sharename, type,
2362                                           opt_comment, perms, opt_maxusers,
2363                                           num_users, path, password, 
2364                                           level, NULL);
2365         return W_ERROR_IS_OK(result) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
2366 }
2367
2368 static int rpc_share_add(int argc, const char **argv)
2369 {
2370         if ((argc < 1) || !strchr(argv[0], '=')) {
2371                 DEBUG(1,("Sharename or path not specified on add\n"));
2372                 return rpc_share_usage(argc, argv);
2373         }
2374         return run_rpc_command(NULL, PI_SRVSVC, 0, 
2375                                rpc_share_add_internals,
2376                                argc, argv);
2377 }
2378
2379 /** 
2380  * Delete a share on a remote RPC server
2381  *
2382  * All parameters are provided by the run_rpc_command function, except for
2383  * argc, argv which are passes through. 
2384  *
2385  * @param domain_sid The domain sid acquired from the remote server
2386  * @param cli A cli_state connected to the server.
2387  * @param mem_ctx Talloc context, destoyed on completion of the function.
2388  * @param argc  Standard main() style argc
2389  * @param argv  Standard main() style argv.  Initial components are already
2390  *              stripped
2391  *
2392  * @return Normal NTSTATUS return.
2393  **/
2394 static NTSTATUS 
2395 rpc_share_del_internals(const DOM_SID *domain_sid, const char *domain_name, 
2396                         struct cli_state *cli,
2397                         TALLOC_CTX *mem_ctx,int argc, const char **argv)
2398 {
2399         WERROR result;
2400
2401         result = cli_srvsvc_net_share_del(cli, mem_ctx, argv[0]);
2402         return W_ERROR_IS_OK(result) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
2403 }
2404
2405 /** 
2406  * Delete a share on a remote RPC server
2407  *
2408  * @param domain_sid The domain sid acquired from the remote server
2409  * @param argc  Standard main() style argc
2410  * @param argv  Standard main() style argv.  Initial components are already
2411  *              stripped
2412  *
2413  * @return A shell status integer (0 for success)
2414  **/
2415 static int rpc_share_delete(int argc, const char **argv)
2416 {
2417         if (argc < 1) {
2418                 DEBUG(1,("Sharename not specified on delete\n"));
2419                 return rpc_share_usage(argc, argv);
2420         }
2421         return run_rpc_command(NULL, PI_SRVSVC, 0, 
2422                                rpc_share_del_internals,
2423                                argc, argv);
2424 }
2425
2426 /**
2427  * Formatted print of share info
2428  *
2429  * @param info1  pointer to SRV_SHARE_INFO_1 to format
2430  **/
2431  
2432 static void display_share_info_1(SRV_SHARE_INFO_1 *info1)
2433 {
2434         fstring netname = "", remark = "";
2435
2436         rpcstr_pull_unistr2_fstring(netname, &info1->info_1_str.uni_netname);
2437         rpcstr_pull_unistr2_fstring(remark, &info1->info_1_str.uni_remark);
2438
2439         if (opt_long_list_entries) {
2440                 d_printf("%-12s %-8.8s %-50s\n",
2441                          netname, share_type[info1->info_1.type], remark);
2442         } else {
2443                 d_printf("%s\n", netname);
2444         }
2445
2446 }
2447
2448 /** 
2449  * List shares on a remote RPC server
2450  *
2451  * All parameters are provided by the run_rpc_command function, except for
2452  * argc, argv which are passes through. 
2453  *
2454  * @param domain_sid The domain sid acquired from the remote server
2455  * @param cli A cli_state connected to the server.
2456  * @param mem_ctx Talloc context, destoyed on completion of the function.
2457  * @param argc  Standard main() style argc
2458  * @param argv  Standard main() style argv.  Initial components are already
2459  *              stripped
2460  *
2461  * @return Normal NTSTATUS return.
2462  **/
2463
2464 static NTSTATUS 
2465 rpc_share_list_internals(const DOM_SID *domain_sid, const char *domain_name, 
2466                          struct cli_state *cli,
2467                          TALLOC_CTX *mem_ctx, int argc, const char **argv)
2468 {
2469         SRV_SHARE_INFO_CTR ctr;
2470         WERROR result;
2471         ENUM_HND hnd;
2472         uint32 preferred_len = 0xffffffff, i;
2473
2474         init_enum_hnd(&hnd, 0);
2475
2476         result = cli_srvsvc_net_share_enum(
2477                 cli, mem_ctx, 1, &ctr, preferred_len, &hnd);
2478
2479         if (!W_ERROR_IS_OK(result))
2480                 goto done;
2481
2482         /* Display results */
2483
2484         if (opt_long_list_entries) {
2485                 d_printf(
2486         "\nEnumerating shared resources (exports) on remote server:\n\n"\
2487         "\nShare name   Type     Description\n"\
2488         "----------   ----     -----------\n");
2489         }
2490         for (i = 0; i < ctr.num_entries; i++)
2491                 display_share_info_1(&ctr.share.info1[i]);
2492  done:
2493         return W_ERROR_IS_OK(result) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
2494 }
2495
2496 /** 
2497  * Migrate shares from a remote RPC server to the local RPC srever
2498  *
2499  * All parameters are provided by the run_rpc_command function, except for
2500  * argc, argv which are passes through. 
2501  *
2502  * @param domain_sid The domain sid acquired from the remote server
2503  * @param cli A cli_state connected to the server.
2504  * @param mem_ctx Talloc context, destoyed on completion of the function.
2505  * @param argc  Standard main() style argc
2506  * @param argv  Standard main() style argv.  Initial components are already
2507  *              stripped
2508  *
2509  * @return Normal NTSTATUS return.
2510  **/
2511 static NTSTATUS 
2512 rpc_share_migrate_shares_internals(const DOM_SID *domain_sid, const char *domain_name, 
2513                                    struct cli_state *cli, TALLOC_CTX *mem_ctx, 
2514                                    int argc, const char **argv)
2515 {
2516         WERROR result;
2517         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
2518         SRV_SHARE_INFO_CTR ctr_src;
2519         ENUM_HND hnd;
2520         uint32 type = 0; /* only allow disk shares to be added */
2521         uint32 num_uses = 0, perms = 0, max_uses = 0;
2522         char *password = NULL; /* don't allow a share password */
2523         uint32 preferred_len = 0xffffffff, i;
2524         BOOL got_dst_srvsvc_pipe = False;
2525         struct cli_state *cli_dst = NULL;
2526         uint32 level = 502; /* includes secdesc */
2527         SEC_DESC *share_sd = NULL;
2528
2529         init_enum_hnd(&hnd, 0);
2530
2531         result = cli_srvsvc_net_share_enum(
2532                         cli, mem_ctx, level, &ctr_src, preferred_len, &hnd);
2533         if (!W_ERROR_IS_OK(result))
2534                 goto done;
2535
2536         /* connect local PI_SRVSVC */
2537         nt_status = connect_pipe(&cli_dst, PI_SRVSVC, &got_dst_srvsvc_pipe);
2538         if (!NT_STATUS_IS_OK(nt_status))
2539                 return nt_status;
2540
2541
2542         for (i = 0; i < ctr_src.num_entries; i++) {
2543
2544                 fstring netname = "", remark = "", path = "";
2545                 /* reset error-code */
2546                 nt_status = NT_STATUS_UNSUCCESSFUL;
2547
2548                 rpcstr_pull_unistr2_fstring(
2549                         netname, &ctr_src.share.info502[i].info_502_str.uni_netname);
2550                 rpcstr_pull_unistr2_fstring(
2551                         remark, &ctr_src.share.info502[i].info_502_str.uni_remark);
2552                 rpcstr_pull_unistr2_fstring(
2553                         path, &ctr_src.share.info502[i].info_502_str.uni_path);
2554                 num_uses        = ctr_src.share.info502[i].info_502.num_uses;
2555                 max_uses        = ctr_src.share.info502[i].info_502.max_uses;
2556                 perms           = ctr_src.share.info502[i].info_502.perms;
2557
2558
2559                 if (opt_acls)
2560                         share_sd = dup_sec_desc(
2561                                 mem_ctx, ctr_src.share.info502[i].info_502_str.sd);
2562
2563                 /* since we do not have NetShareGetInfo implemented in samba3 we 
2564                    only can skip inside the enum-ctr_src */
2565                 if (argc == 1) {
2566                         char *one_share = talloc_strdup(mem_ctx, argv[0]);
2567                         if (!strequal(netname, one_share))
2568                                 continue;
2569                 }
2570
2571                 /* skip builtin shares */
2572                 /* FIXME: should print$ be added too ? */
2573                 if (strequal(netname,"IPC$") || strequal(netname,"ADMIN$") || 
2574                     strequal(netname,"global")) 
2575                         continue;
2576
2577                 /* only work with file-shares */
2578                 if (!cli_send_tconX(cli, netname, "A:", "", 0)) {
2579                         d_printf("skipping   [%s]: not a file share.\n", netname);
2580                         continue;
2581                 }
2582
2583                 if (!cli_tdis(cli)) 
2584                         goto done;
2585
2586
2587                 /* finallly add the share on the dst server 
2588                    please note that samba currently does not allow to 
2589                    add a share without existing directory */
2590
2591                 printf("migrating: [%s], path: %s, comment: %s, %s share-ACLs\n", 
2592                         netname, path, remark, opt_acls ? "including" : "without" );
2593
2594                 if (opt_verbose && opt_acls)
2595                         display_sec_desc(share_sd);
2596
2597                 result = cli_srvsvc_net_share_add(cli_dst, mem_ctx, netname, type,
2598                                                   remark, perms, max_uses,
2599                                                   num_uses, path, password, 
2600                                                   level, share_sd);
2601         
2602                 if (W_ERROR_V(result) == W_ERROR_V(WERR_ALREADY_EXISTS)) {
2603                         printf("           [%s] does already exist\n", netname);
2604                         continue;
2605                 }
2606
2607                 if (!W_ERROR_IS_OK(result)) {
2608                         printf("cannot add share: %s\n", dos_errstr(result));
2609                         goto done;
2610                 }
2611
2612         }
2613
2614         nt_status = NT_STATUS_OK;
2615
2616 done:
2617         if (got_dst_srvsvc_pipe) {
2618                 cli_nt_session_close(cli_dst);
2619                 cli_shutdown(cli_dst);
2620         }
2621
2622         return nt_status;
2623
2624 }
2625
2626 /** 
2627  * Migrate shares from a rpc-server to another
2628  *
2629  * @param argc  Standard main() style argc
2630  * @param argv  Standard main() style argv.  Initial components are already
2631  *              stripped
2632  *
2633  * @return A shell status integer (0 for success)
2634  **/
2635 static int rpc_share_migrate_shares(int argc, const char **argv)
2636 {
2637
2638         if (!opt_host) {
2639                 printf("no server to migrate\n");
2640                 return -1;
2641         }
2642
2643         return run_rpc_command(NULL, PI_SRVSVC, 0, 
2644                                rpc_share_migrate_shares_internals,
2645                                argc, argv);
2646 }
2647
2648 typedef struct copy_clistate {
2649         TALLOC_CTX *mem_ctx;
2650         struct cli_state *cli_share_src;
2651         struct cli_state *cli_share_dst;
2652         const char *cwd;
2653 } copy_clistate;
2654
2655
2656 /**
2657  * Copy a file/dir 
2658  *
2659  * @param f     file_info
2660  * @param mask  current search mask
2661  * @param state arg-pointer
2662  *
2663  **/
2664 static void copy_fn(file_info *f, const char *mask, void *state)
2665 {
2666         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
2667         struct copy_clistate *local_state = (struct copy_clistate *)state;
2668         fstring filename, new_mask, dir;
2669
2670         if (strequal(f->name, ".") || strequal(f->name, "..")) 
2671                 return;
2672
2673         DEBUG(3,("got mask: %s, name: %s\n", mask, f->name));
2674
2675         /* DIRECTORY */
2676         if (f->mode & aDIR) {
2677
2678                 DEBUG(3,("got dir: %s\n", f->name));
2679
2680                 fstrcpy(dir, local_state->cwd);
2681                 fstrcat(dir, "\\");
2682                 fstrcat(dir, f->name);
2683
2684                 /* create that directory */
2685                 nt_status = net_copy_file(local_state->mem_ctx, 
2686                                           local_state->cli_share_src, 
2687                                           local_state->cli_share_dst, 
2688                                           dir, dir, 
2689                                           opt_acls? True : False, 
2690                                           opt_attrs? True : False,
2691                                           opt_timestamps? True : False,
2692                                           False);
2693
2694                 if (!NT_STATUS_IS_OK(nt_status)) 
2695                         printf("could not copy dir %s: %s\n", 
2696                                 dir, nt_errstr(nt_status));
2697
2698                 /* search below that directory */
2699                 fstrcpy(new_mask, dir);
2700                 fstrcat(new_mask, "\\*");
2701
2702                 if (!sync_files(local_state->mem_ctx, 
2703                                 local_state->cli_share_src, 
2704                                 local_state->cli_share_dst, 
2705                                 new_mask, dir))
2706
2707                         printf("could not sync files\n");
2708                         
2709                 return;
2710         }
2711
2712
2713         /* FILE */
2714         fstrcpy(filename, local_state->cwd);
2715         fstrcat(filename, "\\");
2716         fstrcat(filename, f->name);
2717
2718         DEBUG(3,("got file: %s\n", filename));
2719
2720         nt_status = net_copy_file(local_state->mem_ctx, 
2721                                   local_state->cli_share_src, 
2722                                   local_state->cli_share_dst, 
2723                                   filename, filename, 
2724                                   opt_acls? True : False, 
2725                                   opt_attrs? True : False,
2726                                   opt_timestamps? True: False,
2727                                   True);
2728
2729         if (!NT_STATUS_IS_OK(nt_status)) 
2730                 printf("could not copy file %s: %s\n", 
2731                         filename, nt_errstr(nt_status));
2732
2733 }
2734
2735 /**
2736  * sync files, can be called recursivly to list files 
2737  * and then call copy_fn for each file 
2738  *
2739  * @param mem_ctx       TALLOC_CTX
2740  * @param cli_share_src a connected share on the originating server
2741  * @param cli_share_dst a connected share on the destination server
2742  * @param mask          the current search mask
2743  * @param cwd           the current path
2744  *
2745  * @return              Boolean result
2746  **/
2747 BOOL sync_files(TALLOC_CTX *mem_ctx, 
2748                 struct cli_state *cli_share_src, 
2749                 struct cli_state *cli_share_dst,
2750                 pstring mask, fstring cwd)
2751
2752 {
2753
2754         uint16 attribute = aSYSTEM | aHIDDEN | aDIR;
2755         struct copy_clistate clistate;
2756
2757         clistate.mem_ctx        = mem_ctx;
2758         clistate.cli_share_src  = cli_share_src;
2759         clistate.cli_share_dst  = cli_share_dst;
2760         clistate.cwd            = cwd;
2761
2762         DEBUG(3,("calling cli_list with mask: %s\n", mask));
2763
2764         if (cli_list(cli_share_src, mask, attribute, copy_fn, &clistate) == -1) {
2765                 d_printf("listing %s failed with error: %s\n", 
2766                         mask, cli_errstr(cli_share_src));
2767                 return False;
2768         }
2769
2770         return True;
2771 }
2772
2773
2774 /** 
2775  * Sync all files inside a remote share to another share (over smb)
2776  *
2777  * All parameters are provided by the run_rpc_command function, except for
2778  * argc, argv which are passes through. 
2779  *
2780  * @param domain_sid The domain sid acquired from the remote server
2781  * @param cli A cli_state connected to the server.
2782  * @param mem_ctx Talloc context, destoyed on completion of the function.
2783  * @param argc  Standard main() style argc
2784  * @param argv  Standard main() style argv.  Initial components are already
2785  *              stripped
2786  *
2787  * @return Normal NTSTATUS return.
2788  **/
2789 static NTSTATUS 
2790 rpc_share_migrate_files_internals(const DOM_SID *domain_sid, const char *domain_name, 
2791                                   struct cli_state *cli, TALLOC_CTX *mem_ctx,
2792                                   int argc, const char **argv)
2793 {
2794         WERROR result;
2795         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
2796         SRV_SHARE_INFO_CTR ctr_src;
2797         ENUM_HND hnd;
2798         uint32 preferred_len = 0xffffffff, i;
2799         uint32 level = 2;
2800         struct cli_state *cli_share_src = NULL;
2801         struct cli_state *cli_share_dst = NULL;
2802         BOOL got_src_share = False;
2803         BOOL got_dst_share = False;
2804         pstring mask;
2805         char *dst = NULL;
2806
2807         dst = strdup(opt_destination?opt_destination:"127.0.0.1");
2808
2809         init_enum_hnd(&hnd, 0);
2810
2811         result = cli_srvsvc_net_share_enum(
2812                         cli, mem_ctx, level, &ctr_src, preferred_len, &hnd);
2813
2814         if (!W_ERROR_IS_OK(result))
2815                 goto done;
2816
2817         for (i = 0; i < ctr_src.num_entries; i++) {
2818
2819                 fstring netname = "", remark = "", path = "";
2820
2821                 rpcstr_pull_unistr2_fstring(
2822                         netname, &ctr_src.share.info2[i].info_2_str.uni_netname);
2823                 rpcstr_pull_unistr2_fstring(
2824                         remark, &ctr_src.share.info2[i].info_2_str.uni_remark);
2825                 rpcstr_pull_unistr2_fstring(
2826                         path, &ctr_src.share.info2[i].info_2_str.uni_path);
2827
2828                 /* since we do not have NetShareGetInfo implemented in samba3 we 
2829                    only can skip inside the enum-ctr_src */
2830                 if (argc == 1) {
2831                         char *one_share = talloc_strdup(mem_ctx, argv[0]);
2832                         if (!strequal(netname, one_share))
2833                                 continue;
2834                 }
2835
2836                 /* skip builtin and hidden shares 
2837                    In particular, one might not want to mirror whole discs :) */
2838                 if (strequal(netname,"IPC$") || strequal(netname,"ADMIN$"))
2839                         continue;
2840                 
2841                 if (strequal(netname, "print$") || netname[1] == '$') {
2842                         d_printf("skipping   [%s]: builtin/hidden share\n", netname);
2843                         continue;
2844                 }
2845
2846                 if (opt_exclude && in_list(netname, (char *)opt_exclude, False)) {
2847                         printf("excluding  [%s]\n", netname);
2848                         continue;
2849                 } 
2850
2851                 /* only work with file-shares */
2852                 if (!cli_send_tconX(cli, netname, "A:", "", 0)) {
2853                         d_printf("skipping   [%s]: not a file share.\n", netname);
2854                         continue;
2855                 }
2856
2857                 if (!cli_tdis(cli))
2858                         return NT_STATUS_UNSUCCESSFUL;
2859
2860                 printf("syncing    [%s] files and directories %s ACLs, %s DOS Attributes %s\n", 
2861                         netname, 
2862                         opt_acls ? "including" : "without", 
2863                         opt_attrs ? "including" : "without",
2864                         opt_timestamps ? "(preserving timestamps)" : "");
2865
2866
2867                 /* open share source */
2868                 nt_status = connect_to_service(&cli_share_src, &cli->dest_ip, 
2869                                                cli->desthost, netname, "A:");
2870                 if (!NT_STATUS_IS_OK(nt_status))
2871                         goto done;
2872
2873                 got_src_share = True;
2874
2875
2876                 /* open share destination */
2877                 nt_status = connect_to_service(&cli_share_dst, NULL, 
2878                                                dst, netname, "A:");
2879                 if (!NT_STATUS_IS_OK(nt_status))
2880                         goto done;
2881
2882                 got_dst_share = True;
2883
2884
2885                 /* now call the filesync */
2886                 pstrcpy(mask, "\\*");
2887
2888                 if (!sync_files(mem_ctx, cli_share_src, cli_share_dst, mask, NULL)) {
2889                         d_printf("could not sync files for share: %s\n", netname);
2890                         nt_status = NT_STATUS_UNSUCCESSFUL;
2891                         goto done;
2892                 }
2893                 
2894         }
2895
2896         nt_status = NT_STATUS_OK;
2897
2898 done:
2899
2900         if (got_src_share)
2901                 cli_shutdown(cli_share_src);
2902
2903         if (got_dst_share)
2904                 cli_shutdown(cli_share_dst);
2905                 
2906         return nt_status;
2907
2908 }
2909
2910 static int rpc_share_migrate_files(int argc, const char **argv)
2911 {
2912
2913         if (!opt_host) {
2914                 printf("no server to migrate\n");
2915                 return -1;
2916         }
2917
2918         return run_rpc_command(NULL, PI_SRVSVC, 0, 
2919                                rpc_share_migrate_files_internals,
2920                                argc, argv);
2921 }
2922
2923 /** 
2924  * Migrate shares (including share-definitions, share-acls and files with acls/attrs)
2925  * from one server to another
2926  *
2927  * @param argc  Standard main() style argc
2928  * @param argv  Standard main() style argv.  Initial components are already
2929  *              stripped
2930  *
2931  * @return A shell status integer (0 for success)
2932  *
2933  **/
2934 static int rpc_share_migrate_all(int argc, const char **argv)
2935 {
2936         int ret;
2937
2938         if (!opt_host) {
2939                 printf("no server to migrate\n");
2940                 return -1;
2941         }
2942
2943         ret = run_rpc_command(NULL, PI_SRVSVC, 0, rpc_share_migrate_shares_internals, argc, argv);
2944         if (ret)
2945                 return ret;
2946 #if 0
2947         ret = run_rpc_command(NULL, PI_SRVSVC, 0, rpc_share_migrate_shares_security_internals, argc, argv);
2948         if (ret)
2949                 return ret;
2950 #endif
2951         return run_rpc_command(NULL, PI_SRVSVC, 0, rpc_share_migrate_files_internals, argc, argv);
2952 }
2953
2954
2955 /** 
2956  * 'net rpc share migrate' entrypoint.
2957  * @param argc  Standard main() style argc
2958  * @param argv  Standard main() style argv.  Initial components are already
2959  *              stripped
2960  **/
2961 static int rpc_share_migrate(int argc, const char **argv)
2962 {
2963
2964         struct functable func[] = {
2965                 {"all",         rpc_share_migrate_all},
2966                 {"files",       rpc_share_migrate_files},
2967                 {"help",        rpc_share_usage},
2968 /*              {"security",    rpc_share_migrate_security},*/
2969                 {"shares",      rpc_share_migrate_shares},
2970                 {NULL, NULL}
2971         };
2972
2973         return net_run_function(argc, argv, func, rpc_share_usage);
2974 }
2975
2976 struct full_alias {
2977         DOM_SID sid;
2978         int num_members;
2979         DOM_SID *members;
2980 };
2981
2982 static int num_server_aliases;
2983 static struct full_alias *server_aliases;
2984
2985 /*
2986  * Add an alias to the static list.
2987  */
2988 static void push_alias(TALLOC_CTX *mem_ctx, struct full_alias *alias)
2989 {
2990         if (server_aliases == NULL)
2991                 server_aliases = malloc(100 * sizeof(struct full_alias));
2992
2993         server_aliases[num_server_aliases] = *alias;
2994         num_server_aliases += 1;
2995 }
2996
2997 /*
2998  * For a specific domain on the server, fetch all the aliases
2999  * and their members. Add all of them to the server_aliases.
3000  */
3001 static NTSTATUS
3002 rpc_fetch_domain_aliases(struct cli_state *cli, TALLOC_CTX *mem_ctx,
3003                          POLICY_HND *connect_pol,
3004                          const DOM_SID *domain_sid)
3005 {
3006         uint32 start_idx, max_entries, num_entries, i;
3007         struct acct_info *groups;
3008         NTSTATUS result;
3009         POLICY_HND domain_pol;
3010
3011         /* Get domain policy handle */
3012         
3013         result = cli_samr_open_domain(cli, mem_ctx, connect_pol,
3014                                       MAXIMUM_ALLOWED_ACCESS,
3015                                       domain_sid, &domain_pol);
3016         if (!NT_STATUS_IS_OK(result))
3017                 return result;
3018
3019         start_idx = 0;
3020         max_entries = 250;
3021
3022         do {
3023                 result = cli_samr_enum_als_groups(cli, mem_ctx, &domain_pol,
3024                                                   &start_idx, max_entries,
3025                                                   &groups, &num_entries);
3026
3027                 for (i = 0; i < num_entries; i++) {
3028
3029                         POLICY_HND alias_pol;
3030                         struct full_alias alias;
3031                         DOM_SID *members;
3032                         int j;
3033
3034                         result = cli_samr_open_alias(cli, mem_ctx, &domain_pol,
3035                                                      MAXIMUM_ALLOWED_ACCESS,
3036                                                      groups[i].rid,
3037                                                      &alias_pol);
3038                         if (!NT_STATUS_IS_OK(result))
3039                                 goto done;
3040
3041                         result = cli_samr_query_aliasmem(cli, mem_ctx,
3042                                                          &alias_pol,
3043                                                          &alias.num_members,
3044                                                          &members);
3045                         if (!NT_STATUS_IS_OK(result))
3046                                 goto done;
3047
3048                         result = cli_samr_close(cli, mem_ctx, &alias_pol);
3049                         if (!NT_STATUS_IS_OK(result))
3050                                 goto done;
3051
3052                         alias.members = NULL;
3053
3054                         if (alias.num_members > 0) {
3055                                 alias.members = malloc(alias.num_members *
3056                                                        sizeof(DOM_SID));
3057
3058                                 for (j = 0; j < alias.num_members; j++)
3059                                         sid_copy(&alias.members[j],
3060                                                  &members[j]);
3061                         }
3062
3063                         sid_copy(&alias.sid, domain_sid);
3064                         sid_append_rid(&alias.sid, groups[i].rid);
3065
3066                         push_alias(mem_ctx, &alias);
3067                 }
3068         } while (NT_STATUS_EQUAL(result, STATUS_MORE_ENTRIES));
3069
3070         result = NT_STATUS_OK;
3071
3072  done:
3073         cli_samr_close(cli, mem_ctx, &domain_pol);
3074
3075         return result;
3076 }
3077
3078 /*
3079  * Dump server_aliases as names for debugging purposes.
3080  */
3081 static NTSTATUS
3082 rpc_aliaslist_dump(const DOM_SID *domain_sid, const char *domain_name,
3083                    struct cli_state *cli, TALLOC_CTX *mem_ctx, 
3084                    int argc, const char **argv)
3085 {
3086         int i;
3087         NTSTATUS result;
3088         POLICY_HND lsa_pol;
3089
3090         result = cli_lsa_open_policy(cli, mem_ctx, True, 
3091                                      SEC_RIGHTS_MAXIMUM_ALLOWED,
3092                                      &lsa_pol);
3093         if (!NT_STATUS_IS_OK(result))
3094                 return result;
3095
3096         for (i=0; i<num_server_aliases; i++) {
3097                 char **names;
3098                 char **domains;
3099                 uint32 *types;
3100                 int j;
3101
3102                 struct full_alias *alias = &server_aliases[i];
3103
3104                 result = cli_lsa_lookup_sids(cli, mem_ctx, &lsa_pol, 1,
3105                                              &alias->sid,
3106                                              &domains, &names, &types);
3107                 if (!NT_STATUS_IS_OK(result))
3108                         continue;
3109
3110                 DEBUG(1, ("%s\\%s %d: ", domains[0], names[0], types[0]));
3111
3112                 if (alias->num_members == 0) {
3113                         DEBUG(1, ("\n"));
3114                         continue;
3115                 }
3116
3117                 result = cli_lsa_lookup_sids(cli, mem_ctx, &lsa_pol,
3118                                              alias->num_members,
3119                                              alias->members,
3120                                              &domains, &names, &types);
3121
3122                 if (!NT_STATUS_IS_OK(result) &&
3123                     !NT_STATUS_EQUAL(result, STATUS_SOME_UNMAPPED))
3124                         continue;
3125
3126                 for (j=0; j<alias->num_members; j++)
3127                         DEBUG(1, ("%s\\%s (%d); ",
3128                                   domains[j] ? domains[j] : "*unknown*", 
3129                                   names[j] ? names[j] : "*unknown*",types[j]));
3130                 DEBUG(1, ("\n"));
3131         }
3132
3133         cli_lsa_close(cli, mem_ctx, &lsa_pol);
3134
3135         return NT_STATUS_OK;
3136 }
3137
3138 /*
3139  * Fetch a list of all server aliases and their members into
3140  * server_aliases.
3141  */
3142 static NTSTATUS
3143 rpc_aliaslist_internals(const DOM_SID *domain_sid, const char *domain_name,
3144                         struct cli_state *cli, TALLOC_CTX *mem_ctx, 
3145                         int argc, const char **argv)
3146 {
3147         NTSTATUS result;
3148         POLICY_HND connect_pol;
3149         DOM_SID global_sid_Builtin;
3150
3151         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS, 
3152                                   &connect_pol);
3153
3154         if (!NT_STATUS_IS_OK(result))
3155                 goto done;
3156         
3157         string_to_sid(&global_sid_Builtin, "S-1-5-32");
3158
3159         result = rpc_fetch_domain_aliases(cli, mem_ctx, &connect_pol,
3160                                           &global_sid_Builtin);
3161
3162         if (!NT_STATUS_IS_OK(result))
3163                 goto done;
3164         
3165         result = rpc_fetch_domain_aliases(cli, mem_ctx, &connect_pol,
3166                                           domain_sid);
3167
3168         cli_samr_close(cli, mem_ctx, &connect_pol);
3169  done:
3170         return result;
3171 }
3172
3173 static void init_user_token(NT_USER_TOKEN *token, DOM_SID *user_sid)
3174 {
3175         DOM_SID global_sid_World;
3176         DOM_SID global_sid_Network;
3177         DOM_SID global_sid_Authenticated_Users;
3178
3179         string_to_sid(&global_sid_World, "S-1-1-0");
3180         string_to_sid(&global_sid_Network, "S-1-5-2");
3181         string_to_sid(&global_sid_Authenticated_Users, "S-1-5-11");
3182
3183         token->num_sids = 4;
3184
3185         token->user_sids = malloc(4 * sizeof(DOM_SID));
3186
3187         token->user_sids[0] = *user_sid;
3188         sid_copy(&token->user_sids[1], &global_sid_World);
3189         sid_copy(&token->user_sids[2], &global_sid_Network);
3190         sid_copy(&token->user_sids[3], &global_sid_Authenticated_Users);
3191 }
3192
3193 static void free_user_token(NT_USER_TOKEN *token)
3194 {
3195         SAFE_FREE(token->user_sids);
3196 }
3197
3198 static BOOL is_sid_in_token(NT_USER_TOKEN *token, DOM_SID *sid)
3199 {
3200         int i;
3201
3202         for (i=0; i<token->num_sids; i++) {
3203                 if (sid_compare(sid, &token->user_sids[i]) == 0)
3204                         return True;
3205         }
3206         return False;
3207 }
3208
3209 static void add_sid_to_token(NT_USER_TOKEN *token, DOM_SID *sid)
3210 {
3211         if (is_sid_in_token(token, sid))
3212                 return;
3213
3214         token->user_sids = Realloc(token->user_sids,
3215                                    (token->num_sids+1) * sizeof(DOM_SID));
3216
3217         sid_copy(&token->user_sids[token->num_sids], sid);
3218
3219         token->num_sids += 1;
3220 }
3221
3222 struct user_token {
3223         fstring name;
3224         NT_USER_TOKEN token;
3225 };
3226
3227 static void dump_user_token(struct user_token *token)
3228 {
3229         int i;
3230
3231         d_printf("%s\n", token->name);
3232
3233         for (i=0; i<token->token.num_sids; i++) {
3234                 d_printf(" %s\n", sid_string_static(&token->token.user_sids[i]));
3235         }
3236 }
3237
3238 static BOOL is_alias_member(DOM_SID *sid, struct full_alias *alias)
3239 {
3240         int i;
3241
3242         for (i=0; i<alias->num_members; i++) {
3243                 if (sid_compare(sid, &alias->members[i]) == 0)
3244                         return True;
3245         }
3246
3247         return False;
3248 }
3249
3250 static void collect_sid_memberships(NT_USER_TOKEN *token, DOM_SID sid)
3251 {
3252         int i;
3253
3254         for (i=0; i<num_server_aliases; i++) {
3255                 if (is_alias_member(&sid, &server_aliases[i]))
3256                         add_sid_to_token(token, &server_aliases[i].sid);
3257         }
3258 }
3259
3260 /*
3261  * We got a user token with all the SIDs we can know about without asking the
3262  * server directly. These are the user and domain group sids. All of these can
3263  * be members of aliases. So scan the list of aliases for each of the SIDs and
3264  * add them to the token.
3265  */
3266
3267 static void collect_alias_memberships(NT_USER_TOKEN *token)
3268 {
3269         int num_global_sids = token->num_sids;
3270         int i;
3271
3272         for (i=0; i<num_global_sids; i++) {
3273                 collect_sid_memberships(token, token->user_sids[i]);
3274         }
3275 }
3276
3277 static BOOL get_user_sids(const char *domain, const char *user,
3278                           NT_USER_TOKEN *token)
3279 {
3280         struct winbindd_request request;
3281         struct winbindd_response response;
3282         fstring full_name;
3283         NSS_STATUS result;
3284
3285         DOM_SID user_sid;
3286
3287         int i;
3288
3289         fstr_sprintf(full_name, "%s%c%s",
3290                      domain, *lp_winbind_separator(), user);
3291
3292         /* First let's find out the user sid */
3293
3294         ZERO_STRUCT(request);
3295         ZERO_STRUCT(response);
3296
3297         fstrcpy(request.data.name.dom_name, domain);
3298         fstrcpy(request.data.name.name, user);
3299
3300         result = winbindd_request(WINBINDD_LOOKUPNAME, &request, &response);
3301
3302         if (result != NSS_STATUS_SUCCESS) {
3303                 DEBUG(1, ("winbind could not find %s\n", full_name));
3304                 return False;
3305         }
3306
3307         if (response.data.sid.type != SID_NAME_USER) {
3308                 DEBUG(1, ("%s is not a user\n", full_name));
3309                 return False;
3310         }
3311
3312         string_to_sid(&user_sid, response.data.sid.sid);
3313
3314         init_user_token(token, &user_sid);
3315
3316         /* And now the groups winbind knows about */
3317
3318         ZERO_STRUCT(response);
3319
3320         fstrcpy(request.data.username, full_name);
3321
3322         result = winbindd_request(WINBINDD_GETGROUPS, &request, &response);
3323
3324         if (result != NSS_STATUS_SUCCESS) {
3325                 DEBUG(1, ("winbind could not get groups of %s\n", full_name));
3326                 return False;
3327         }
3328
3329         for (i = 0; i < response.data.num_entries; i++) {
3330                 gid_t gid = ((gid_t *)response.extra_data)[i];
3331                 DOM_SID sid;
3332
3333                 struct winbindd_request sidrequest;
3334                 struct winbindd_response sidresponse;
3335
3336                 ZERO_STRUCT(sidrequest);
3337                 ZERO_STRUCT(sidresponse);
3338
3339                 sidrequest.data.gid = gid;
3340
3341                 result = winbindd_request(WINBINDD_GID_TO_SID,
3342                                           &sidrequest, &sidresponse);
3343
3344                 if (result != NSS_STATUS_SUCCESS) {
3345                         DEBUG(1, ("winbind could not find SID of gid %d\n",
3346                                   gid));
3347                         return False;
3348                 }
3349
3350                 DEBUG(3, (" %s\n", sidresponse.data.sid.sid));
3351
3352                 string_to_sid(&sid, sidresponse.data.sid.sid);
3353                 add_sid_to_token(token, &sid);
3354         }
3355
3356         SAFE_FREE(response.extra_data);
3357
3358         return True;
3359 }
3360         
3361 /**
3362  * Get a list of all user tokens we want to look at
3363  **/
3364 static BOOL get_user_tokens(int *num_tokens, struct user_token **user_tokens)
3365 {
3366         struct winbindd_request request;
3367         struct winbindd_response response;
3368         const char *extra_data;
3369         fstring name;
3370         int i;
3371         struct user_token *result;
3372
3373         /* Send request to winbind daemon */
3374
3375         ZERO_STRUCT(request);
3376         ZERO_STRUCT(response);
3377         
3378         if (winbindd_request(WINBINDD_LIST_USERS, &request, &response) !=
3379             NSS_STATUS_SUCCESS)
3380                 return False;
3381
3382         /* Look through extra data */
3383
3384         if (!response.extra_data)
3385                 return False;
3386
3387         extra_data = (const char *)response.extra_data;
3388         *num_tokens = 0;
3389
3390         while(next_token(&extra_data, name, ",", sizeof(fstring))) {
3391                 *num_tokens += 1;
3392         }
3393
3394         result = malloc(*num_tokens * sizeof(struct user_token));
3395
3396         if (result == NULL) {
3397                 DEBUG(1, ("Could not malloc sid array\n"));
3398                 return False;
3399         }
3400
3401         extra_data = (const char *)response.extra_data;
3402         i=0;
3403
3404         while(next_token(&extra_data, name, ",", sizeof(fstring))) {
3405
3406                 fstring domain, user;
3407                 char *p;
3408
3409                 fstrcpy(result[i].name, name);
3410
3411                 p = strchr(name, *lp_winbind_separator());
3412
3413                 DEBUG(3, ("%s\n", name));
3414
3415                 if (p == NULL)
3416                         continue;
3417
3418                 *p++ = '\0';
3419
3420                 fstrcpy(domain, name);
3421                 strupper_m(domain);
3422                 fstrcpy(user, p);
3423
3424                 get_user_sids(domain, user, &(result[i].token));
3425                 i+=1;
3426         }
3427         
3428         SAFE_FREE(response.extra_data);
3429
3430         *user_tokens = result;
3431
3432         return True;
3433 }
3434
3435 static BOOL get_user_tokens_from_file(FILE *f,
3436                                       int *num_tokens,
3437                                       struct user_token **tokens)
3438 {
3439         struct user_token *token = NULL;
3440
3441         while (!feof(f)) {
3442                 fstring line;
3443
3444                 if (fgets(line, sizeof(line)-1, f) == NULL) {
3445                         return True;
3446                 }
3447
3448                 if (line[strlen(line)-1] == '\n')
3449                         line[strlen(line)-1] = '\0';
3450
3451                 if (line[0] == ' ') {
3452                         /* We have a SID */
3453
3454                         DOM_SID sid;
3455                         string_to_sid(&sid, &line[1]);
3456
3457                         if (token == NULL) {
3458                                 DEBUG(0, ("File does not begin with username"));
3459                                 return False;
3460                         }
3461
3462                         add_sid_to_token(&token->token, &sid);
3463                         continue;
3464                 }
3465
3466                 /* And a new user... */
3467
3468                 *num_tokens += 1;
3469                 *tokens = Realloc(*tokens,
3470                                   *num_tokens *
3471                                   sizeof(struct user_token));
3472                 if (*tokens == NULL) {
3473                         DEBUG(0, ("Could not realloc tokens\n"));
3474                         return False;
3475                 }
3476
3477                 token = &((*tokens)[*num_tokens-1]);
3478
3479                 fstrcpy(token->name, line);
3480                 token->token.num_sids = 0;
3481                 token->token.user_sids = NULL;
3482                 continue;
3483         }
3484         
3485         return False;
3486 }
3487
3488
3489 /*
3490  * Show the list of all users that have access to a share
3491  */
3492
3493 static void show_userlist(struct cli_state *cli,
3494                           TALLOC_CTX *mem_ctx, const char *netname,
3495                           int num_tokens, struct user_token *tokens)
3496 {
3497         int fnum;
3498         SEC_DESC *share_sd = NULL;
3499         SEC_DESC *root_sd = NULL;
3500         int i;
3501         SRV_SHARE_INFO info;
3502         WERROR result;
3503         uint16 cnum;
3504
3505         result = cli_srvsvc_net_share_get_info(cli, mem_ctx, netname,
3506                                                502, &info);
3507
3508         if (!W_ERROR_IS_OK(result)) {
3509                 DEBUG(1, ("Coult not query secdesc for share %s\n",
3510                           netname));
3511                 return;
3512         }
3513
3514         share_sd = info.share.info502.info_502_str.sd;
3515         if (share_sd == NULL) {
3516                 DEBUG(1, ("Got no secdesc for share %s\n",
3517                           netname));
3518         }
3519
3520         cnum = cli->cnum;
3521
3522         if (!cli_send_tconX(cli, netname, "A:", "", 0)) {
3523                 return;
3524         }
3525
3526         fnum = cli_nt_create(cli, "\\", READ_CONTROL_ACCESS);
3527
3528         if (fnum != -1) {
3529                 root_sd = cli_query_secdesc(cli, fnum, mem_ctx);
3530         }
3531
3532         for (i=0; i<num_tokens; i++) {
3533                 uint32 acc_granted;
3534                 NTSTATUS status;
3535
3536                 if (share_sd != NULL) {
3537                         if (!se_access_check(share_sd, &tokens[i].token,
3538                                              1, &acc_granted, &status)) {
3539                                 DEBUG(1, ("Could not check share_sd for "
3540                                           "user %s\n",
3541                                           tokens[i].name));
3542                                 continue;
3543                         }
3544
3545                         if (!NT_STATUS_IS_OK(status))
3546                                 continue;
3547                 }
3548
3549                 if (root_sd == NULL) {
3550                         d_printf(" %s\n", tokens[i].name);
3551                         continue;
3552                 }
3553
3554                 if (!se_access_check(root_sd, &tokens[i].token,
3555                                      1, &acc_granted, &status)) {
3556                         DEBUG(1, ("Could not check root_sd for user %s\n",
3557                                   tokens[i].name));
3558                         continue;
3559                 }
3560
3561                 if (!NT_STATUS_IS_OK(status))
3562                         continue;
3563
3564                 d_printf(" %s\n", tokens[i].name);
3565         }
3566
3567         if (fnum != -1)
3568                 cli_close(cli, fnum);
3569         cli_tdis(cli);
3570         cli->cnum = cnum;
3571         
3572         return;
3573 }
3574
3575 struct share_list {
3576         int num_shares;
3577         char **shares;
3578 };
3579
3580 static void collect_share(const char *name, uint32 m,
3581                           const char *comment, void *state)
3582 {
3583         struct share_list *share_list = (struct share_list *)state;
3584
3585         if (m != STYPE_DISKTREE)
3586                 return;
3587
3588         share_list->num_shares += 1;
3589         share_list->shares = Realloc(share_list->shares,
3590                                      share_list->num_shares * sizeof(char *));
3591         share_list->shares[share_list->num_shares-1] = strdup(name);
3592 }
3593
3594 static void rpc_share_userlist_usage(void)
3595 {
3596         return;
3597 }
3598         
3599 /** 
3600  * List shares on a remote RPC server, including the security descriptors
3601  *
3602  * All parameters are provided by the run_rpc_command function, except for
3603  * argc, argv which are passes through. 
3604  *
3605  * @param domain_sid The domain sid acquired from the remote server
3606  * @param cli A cli_state connected to the server.
3607  * @param mem_ctx Talloc context, destoyed on completion of the function.
3608  * @param argc  Standard main() style argc
3609  * @param argv  Standard main() style argv.  Initial components are already
3610  *              stripped
3611  *
3612  * @return Normal NTSTATUS return.
3613  **/
3614
3615 static NTSTATUS 
3616 rpc_share_allowedusers_internals(const DOM_SID *domain_sid,
3617                                  const char *domain_name,
3618                                  struct cli_state *cli,
3619                                  TALLOC_CTX *mem_ctx,
3620                                  int argc, const char **argv)
3621 {
3622         int ret;
3623         BOOL r;
3624         ENUM_HND hnd;
3625         uint32 i;
3626         FILE *f;
3627
3628         struct user_token *tokens = NULL;
3629         int num_tokens = 0;
3630
3631         struct share_list share_list;
3632
3633         if (argc > 1) {
3634                 rpc_share_userlist_usage();
3635                 return NT_STATUS_UNSUCCESSFUL;
3636         }
3637
3638         if (argc == 0) {
3639                 f = stdin;
3640         } else {
3641                 f = fopen(argv[0], "r");
3642         }
3643
3644         if (f == NULL) {
3645                 DEBUG(0, ("Could not open userlist: %s\n", strerror(errno)));
3646                 return NT_STATUS_UNSUCCESSFUL;
3647         }
3648
3649         r = get_user_tokens_from_file(f, &num_tokens, &tokens);
3650
3651         if (f != stdin)
3652                 fclose(f);
3653
3654         if (!r) {
3655                 DEBUG(0, ("Could not read users from file\n"));
3656                 return NT_STATUS_UNSUCCESSFUL;
3657         }
3658
3659         for (i=0; i<num_tokens; i++)
3660                 collect_alias_memberships(&tokens[i].token);
3661
3662         init_enum_hnd(&hnd, 0);
3663
3664         share_list.num_shares = 0;
3665         share_list.shares = NULL;
3666
3667         ret = cli_RNetShareEnum(cli, collect_share, &share_list);
3668
3669         if (ret == -1) {
3670                 DEBUG(0, ("Error returning browse list: %s\n",
3671                           cli_errstr(cli)));
3672                 goto done;
3673         }
3674
3675         for (i = 0; i < share_list.num_shares; i++) {
3676                 char *netname = share_list.shares[i];
3677
3678                 if (netname[strlen(netname)-1] == '$')
3679                         continue;
3680
3681                 d_printf("%s\n", netname);
3682
3683                 show_userlist(cli, mem_ctx, netname,
3684                               num_tokens, tokens);
3685         }
3686  done:
3687         for (i=0; i<num_tokens; i++) {
3688                 free_user_token(&tokens[i].token);
3689         }
3690         SAFE_FREE(tokens);
3691         SAFE_FREE(share_list.shares);
3692
3693         return NT_STATUS_OK;
3694 }
3695
3696 static int
3697 rpc_share_allowedusers(int argc, const char **argv)
3698 {
3699         int result;
3700
3701         result = run_rpc_command(NULL, PI_SAMR, 0,
3702                                  rpc_aliaslist_internals,
3703                                  argc, argv);
3704         if (result != 0)
3705                 return result;
3706
3707         result = run_rpc_command(NULL, PI_LSARPC, 0,
3708                                  rpc_aliaslist_dump,
3709                                  argc, argv);
3710         if (result != 0)
3711                 return result;
3712
3713         return run_rpc_command(NULL, PI_SRVSVC, 0,
3714                                rpc_share_allowedusers_internals,
3715                                argc, argv);
3716 }
3717
3718 int net_usersidlist(int argc, const char **argv)
3719 {
3720         int num_tokens = 0;
3721         struct user_token *tokens = NULL;
3722         int i;
3723
3724         if (argc != 0) {
3725                 net_usersidlist_usage(argc, argv);
3726                 return 0;
3727         }
3728
3729         if (!get_user_tokens(&num_tokens, &tokens)) {
3730                 DEBUG(0, ("Could not get the user/sid list\n"));
3731                 return 0;
3732         }
3733
3734         for (i=0; i<num_tokens; i++) {
3735                 dump_user_token(&tokens[i]);
3736                 free_user_token(&tokens[i].token);
3737         }
3738
3739         SAFE_FREE(tokens);
3740         return 1;
3741 }
3742
3743 int net_usersidlist_usage(int argc, const char **argv)
3744 {
3745         d_printf("net usersidlist\n"
3746                  "\tprints out a list of all users the running winbind knows\n"
3747                  "\tabout, together with all their SIDs. This is used as\n"
3748                  "\tinput to the 'net rpc share allowedusers' command.\n\n");
3749
3750         net_common_flags_usage(argc, argv);
3751         return -1;
3752 }
3753
3754 /** 
3755  * 'net rpc share' entrypoint.
3756  * @param argc  Standard main() style argc
3757  * @param argv  Standard main() style argv.  Initial components are already
3758  *              stripped
3759  **/
3760
3761 int net_rpc_share(int argc, const char **argv) 
3762 {
3763         struct functable func[] = {
3764                 {"add", rpc_share_add},
3765                 {"delete", rpc_share_delete},
3766                 {"allowedusers", rpc_share_allowedusers},
3767                 {"migrate", rpc_share_migrate},
3768                 {NULL, NULL}
3769         };
3770
3771         if (argc == 0)
3772                 return run_rpc_command(NULL, PI_SRVSVC, 0, 
3773                                        rpc_share_list_internals,
3774                                        argc, argv);
3775
3776         return net_run_function(argc, argv, func, rpc_share_usage);
3777 }
3778
3779 /****************************************************************************/
3780
3781 static int rpc_file_usage(int argc, const char **argv)
3782 {
3783         return net_help_file(argc, argv);
3784 }
3785
3786 /** 
3787  * Close a file on a remote RPC server
3788  *
3789  * All parameters are provided by the run_rpc_command function, except for
3790  * argc, argv which are passes through. 
3791  *
3792  * @param domain_sid The domain sid acquired from the remote server
3793  * @param cli A cli_state connected to the server.
3794  * @param mem_ctx Talloc context, destoyed on completion of the function.
3795  * @param argc  Standard main() style argc
3796  * @param argv  Standard main() style argv.  Initial components are already
3797  *              stripped
3798  *
3799  * @return Normal NTSTATUS return.
3800  **/
3801 static NTSTATUS 
3802 rpc_file_close_internals(const DOM_SID *domain_sid, const char *domain_name, 
3803                          struct cli_state *cli,
3804                          TALLOC_CTX *mem_ctx, int argc, const char **argv)
3805 {
3806         WERROR result;
3807         result = cli_srvsvc_net_file_close(cli, mem_ctx, atoi(argv[0]));
3808         return W_ERROR_IS_OK(result) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3809 }
3810
3811 /** 
3812  * Close a file on a remote RPC server
3813  *
3814  * @param argc  Standard main() style argc
3815  * @param argv  Standard main() style argv.  Initial components are already
3816  *              stripped
3817  *
3818  * @return A shell status integer (0 for success)
3819  **/
3820 static int rpc_file_close(int argc, const char **argv)
3821 {
3822         if (argc < 1) {
3823                 DEBUG(1, ("No fileid given on close\n"));
3824                 return(rpc_file_usage(argc, argv));
3825         }
3826
3827         return run_rpc_command(NULL, PI_SRVSVC, 0, 
3828                                rpc_file_close_internals,
3829                                argc, argv);
3830 }
3831
3832 /** 
3833  * Formatted print of open file info 
3834  *
3835  * @param info3  FILE_INFO_3 contents
3836  * @param str3   strings for FILE_INFO_3
3837  **/
3838
3839 static void display_file_info_3(FILE_INFO_3 *info3, FILE_INFO_3_STR *str3)
3840 {
3841         fstring user = "", path = "";
3842
3843         rpcstr_pull_unistr2_fstring(user, &str3->uni_user_name);
3844         rpcstr_pull_unistr2_fstring(path, &str3->uni_path_name);
3845
3846         d_printf("%-7.1d %-20.20s 0x%-4.2x %-6.1d %s\n",
3847                  info3->id, user, info3->perms, info3->num_locks, path);
3848 }
3849
3850 /** 
3851  * List open files on a remote RPC server
3852  *
3853  * All parameters are provided by the run_rpc_command function, except for
3854  * argc, argv which are passes through. 
3855  *
3856  * @param domain_sid The domain sid acquired from the remote server
3857  * @param cli A cli_state connected to the server.
3858  * @param mem_ctx Talloc context, destoyed on completion of the function.
3859  * @param argc  Standard main() style argc
3860  * @param argv  Standard main() style argv.  Initial components are already
3861  *              stripped
3862  *
3863  * @return Normal NTSTATUS return.
3864  **/
3865
3866 static NTSTATUS 
3867 rpc_file_list_internals(const DOM_SID *domain_sid, const char *domain_name, 
3868                         struct cli_state *cli,
3869                         TALLOC_CTX *mem_ctx, int argc, const char **argv)
3870 {
3871         SRV_FILE_INFO_CTR ctr;
3872         WERROR result;
3873         ENUM_HND hnd;
3874         uint32 preferred_len = 0xffffffff, i;
3875         const char *username=NULL;
3876
3877         init_enum_hnd(&hnd, 0);
3878
3879         /* if argc > 0, must be user command */
3880         if (argc > 0)
3881                 username = smb_xstrdup(argv[0]);
3882                 
3883         result = cli_srvsvc_net_file_enum(
3884                 cli, mem_ctx, 3, username, &ctr, preferred_len, &hnd);
3885
3886         if (!W_ERROR_IS_OK(result))
3887                 goto done;
3888
3889         /* Display results */
3890
3891         d_printf(
3892                  "\nEnumerating open files on remote server:\n\n"\
3893                  "\nFileId  Opened by            Perms  Locks  Path"\
3894                  "\n------  ---------            -----  -----  ---- \n");
3895         for (i = 0; i < ctr.num_entries; i++)
3896                 display_file_info_3(&ctr.file.info3[i].info_3, 
3897                                     &ctr.file.info3[i].info_3_str);
3898  done:
3899         return W_ERROR_IS_OK(result) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3900 }
3901
3902
3903 /** 
3904  * List files for a user on a remote RPC server
3905  *
3906  * @param argc  Standard main() style argc
3907  * @param argv  Standard main() style argv.  Initial components are already
3908  *              stripped
3909  *
3910  * @return A shell status integer (0 for success)
3911  **/
3912 static int rpc_file_user(int argc, const char **argv)
3913 {
3914         if (argc < 1) {
3915                 DEBUG(1, ("No username given\n"));
3916                 return(rpc_file_usage(argc, argv));
3917         }
3918
3919         return run_rpc_command(NULL, PI_SRVSVC, 0, 
3920                                rpc_file_list_internals,
3921                                argc, argv);
3922 }
3923
3924
3925 /** 
3926  * 'net rpc file' entrypoint.
3927  * @param argc  Standard main() style argc
3928  * @param argv  Standard main() style argv.  Initial components are already
3929  *              stripped
3930  **/
3931
3932 int net_rpc_file(int argc, const char **argv) 
3933 {
3934         struct functable func[] = {
3935                 {"close", rpc_file_close},
3936                 {"user", rpc_file_user},
3937 #if 0
3938                 {"info", rpc_file_info},
3939 #endif
3940                 {NULL, NULL}
3941         };
3942
3943         if (argc == 0)
3944                 return run_rpc_command(NULL, PI_SRVSVC, 0, 
3945                                        rpc_file_list_internals,
3946                                        argc, argv);
3947
3948         return net_run_function(argc, argv, func, rpc_file_usage);
3949 }
3950
3951 /****************************************************************************/
3952
3953
3954
3955 /** 
3956  * ABORT the shutdown of a remote RPC Server over, initshutdown pipe
3957  *
3958  * All parameters are provided by the run_rpc_command function, except for
3959  * argc, argv which are passed through. 
3960  *
3961  * @param domain_sid The domain sid aquired from the remote server
3962  * @param cli A cli_state connected to the server.
3963  * @param mem_ctx Talloc context, destoyed on compleation of the function.
3964  * @param argc  Standard main() style argc
3965  * @param argv  Standard main() style argv.  Initial components are already
3966  *              stripped
3967  *
3968  * @return Normal NTSTATUS return.
3969  **/
3970
3971 static NTSTATUS rpc_shutdown_abort_internals(const DOM_SID *domain_sid, 
3972                                              const char *domain_name, 
3973                                              struct cli_state *cli, 
3974                                              TALLOC_CTX *mem_ctx, 
3975                                              int argc, const char **argv) 
3976 {
3977         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
3978         
3979         result = cli_shutdown_abort(cli, mem_ctx);
3980         
3981         if (NT_STATUS_IS_OK(result))
3982                 DEBUG(5,("cmd_shutdown_abort: query succeeded\n"));
3983         else
3984                 DEBUG(5,("cmd_shutdown_abort: query failed\n"));
3985         
3986         return result;
3987 }
3988
3989
3990 /** 
3991  * ABORT the shutdown of a remote RPC Server,  over winreg pipe
3992  *
3993  * All parameters are provided by the run_rpc_command function, except for
3994  * argc, argv which are passed through. 
3995  *
3996  * @param domain_sid The domain sid aquired from the remote server
3997  * @param cli A cli_state connected to the server.
3998  * @param mem_ctx Talloc context, destoyed on compleation of the function.
3999  * @param argc  Standard main() style argc
4000  * @param argv  Standard main() style argv.  Initial components are already
4001  *              stripped
4002  *
4003  * @return Normal NTSTATUS return.
4004  **/
4005
4006 static NTSTATUS rpc_reg_shutdown_abort_internals(const DOM_SID *domain_sid, 
4007                                                  const char *domain_name, 
4008                                                  struct cli_state *cli, 
4009                                                  TALLOC_CTX *mem_ctx, 
4010                                                  int argc, const char **argv) 
4011 {
4012         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
4013         
4014         result = cli_reg_abort_shutdown(cli, mem_ctx);
4015         
4016         if (NT_STATUS_IS_OK(result))
4017                 DEBUG(5,("cmd_reg_abort_shutdown: query succeeded\n"));
4018         else
4019                 DEBUG(5,("cmd_reg_abort_shutdown: query failed\n"));
4020         
4021         return result;
4022 }
4023
4024 /** 
4025  * ABORT the Shut down of a remote RPC server
4026  *
4027  * @param argc  Standard main() style argc
4028  * @param argv  Standard main() style argv.  Initial components are already
4029  *              stripped
4030  *
4031  * @return A shell status integer (0 for success)
4032  **/
4033
4034 static int rpc_shutdown_abort(int argc, const char **argv) 
4035 {
4036         int rc = run_rpc_command(NULL, PI_SHUTDOWN, 0, 
4037                                  rpc_shutdown_abort_internals,
4038                                  argc, argv);
4039
4040         if (rc == 0)
4041                 return rc;
4042
4043         DEBUG(1, ("initshutdown pipe didn't work, trying winreg pipe\n"));
4044
4045         return run_rpc_command(NULL, PI_WINREG, 0, 
4046                                rpc_reg_shutdown_abort_internals,
4047                                argc, argv);
4048 }
4049
4050 /** 
4051  * Shut down a remote RPC Server
4052  *
4053  * All parameters are provided by the run_rpc_command function, except for
4054  * argc, argv which are passes through. 
4055  *
4056  * @param domain_sid The domain sid aquired from the remote server
4057  * @param cli A cli_state connected to the server.
4058  * @param mem_ctx Talloc context, destoyed on compleation of the function.
4059  * @param argc  Standard main() style argc
4060  * @param argc  Standard main() style argv.  Initial components are already
4061  *              stripped
4062  *
4063  * @return Normal NTSTATUS return.
4064  **/
4065
4066 static NTSTATUS rpc_shutdown_internals(const DOM_SID *domain_sid, 
4067                                        const char *domain_name, 
4068                                        struct cli_state *cli, TALLOC_CTX *mem_ctx, 
4069                                        int argc, const char **argv) 
4070 {
4071         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
4072         const char *msg = "This machine will be shutdown shortly";
4073         uint32 timeout = 20;
4074 #if 0
4075         poptContext pc;
4076         int rc;
4077
4078         struct poptOption long_options[] = {
4079                 {"message",    'm', POPT_ARG_STRING, &msg},
4080                 {"timeout",    't', POPT_ARG_INT,    &timeout},
4081                 {"reboot",     'r', POPT_ARG_NONE,   &reboot},
4082                 {"force",      'f', POPT_ARG_NONE,   &force},
4083                 { 0, 0, 0, 0}
4084         };
4085
4086         pc = poptGetContext(NULL, argc, (const char **) argv, long_options, 
4087                             POPT_CONTEXT_KEEP_FIRST);
4088
4089         rc = poptGetNextOpt(pc);
4090         
4091         if (rc < -1) {
4092                 /* an error occurred during option processing */
4093                 DEBUG(0, ("%s: %s\n",
4094                           poptBadOption(pc, POPT_BADOPTION_NOALIAS),
4095                           poptStrerror(rc)));
4096                 return NT_STATUS_INVALID_PARAMETER;
4097         }
4098 #endif
4099         if (opt_comment) {
4100                 msg = opt_comment;
4101         }
4102         if (opt_timeout) {
4103                 timeout = opt_timeout;
4104         }
4105
4106         /* create an entry */
4107         result = cli_reg_shutdown(cli, mem_ctx, msg, timeout, opt_reboot, opt_force);
4108
4109         if (NT_STATUS_IS_OK(result))
4110                 DEBUG(5,("Shutdown of remote machine succeeded\n"));
4111         else
4112                 DEBUG(0,("Shutdown of remote machine failed!\n"));
4113
4114         return result;
4115 }
4116
4117 /** 
4118  * Shut down a remote RPC server
4119  *
4120  * @param argc  Standard main() style argc
4121  * @param argc  Standard main() style argv.  Initial components are already
4122  *              stripped
4123  *
4124  * @return A shell status integer (0 for success)
4125  **/
4126
4127 static int rpc_shutdown(int argc, const char **argv) 
4128 {
4129         return run_rpc_command(NULL, PI_WINREG, 0, rpc_shutdown_internals,
4130                                        argc, argv);
4131 }
4132
4133 /***************************************************************************
4134   NT Domain trusts code (i.e. 'net rpc trustdom' functionality)
4135   
4136  ***************************************************************************/
4137
4138 /**
4139  * Add interdomain trust account to the RPC server.
4140  * All parameters (except for argc and argv) are passed by run_rpc_command
4141  * function.
4142  *
4143  * @param domain_sid The domain sid acquired from the server
4144  * @param cli A cli_state connected to the server.
4145  * @param mem_ctx Talloc context, destoyed on completion of the function.
4146  * @param argc  Standard main() style argc
4147  * @param argc  Standard main() style argv.  Initial components are already
4148  *              stripped
4149  *
4150  * @return normal NTSTATUS return code
4151  */
4152
4153 static NTSTATUS rpc_trustdom_add_internals(const DOM_SID *domain_sid, 
4154                                            const char *domain_name, 
4155                                            struct cli_state *cli, TALLOC_CTX *mem_ctx, 
4156                                            int argc, const char **argv) {
4157
4158         POLICY_HND connect_pol, domain_pol, user_pol;
4159         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
4160         char *acct_name;
4161         uint16 acb_info;
4162         uint32 unknown, user_rid;
4163
4164         if (argc != 2) {
4165                 d_printf("Usage: net rpc trustdom add <domain_name> <pw>\n");
4166                 return NT_STATUS_INVALID_PARAMETER;
4167         }
4168
4169         /* 
4170          * Make valid trusting domain account (ie. uppercased and with '$' appended)
4171          */
4172          
4173         if (asprintf(&acct_name, "%s$", argv[0]) < 0) {
4174                 return NT_STATUS_NO_MEMORY;
4175         }
4176
4177         strupper_m(acct_name);
4178
4179         /* Get samr policy handle */
4180         result = cli_samr_connect(cli, mem_ctx, MAXIMUM_ALLOWED_ACCESS,
4181                                   &connect_pol);
4182         if (!NT_STATUS_IS_OK(result)) {
4183                 goto done;
4184         }
4185         
4186         /* Get domain policy handle */
4187         result = cli_samr_open_domain(cli, mem_ctx, &connect_pol,
4188                                       MAXIMUM_ALLOWED_ACCESS,
4189                                       domain_sid, &domain_pol);
4190         if (!NT_STATUS_IS_OK(result)) {
4191                 goto done;
4192         }
4193
4194         /* Create trusting domain's account */
4195         acb_info = ACB_DOMTRUST;
4196         unknown = 0xe00500b0; /* No idea what this is - a permission mask?
4197                                  mimir: yes, most probably it is */
4198
4199         result = cli_samr_create_dom_user(cli, mem_ctx, &domain_pol,
4200                                           acct_name, acb_info, unknown,
4201                                           &user_pol, &user_rid);
4202         if (!NT_STATUS_IS_OK(result)) {
4203                 goto done;
4204         }
4205
4206         {
4207                 SAM_USERINFO_CTR ctr;
4208                 SAM_USER_INFO_24 p24;
4209                 uchar pwbuf[516];
4210
4211                 encode_pw_buffer((char *)pwbuf, argv[1], STR_UNICODE);
4212
4213                 ZERO_STRUCT(ctr);
4214                 ZERO_STRUCT(p24);
4215
4216                 init_sam_user_info24(&p24, (char *)pwbuf, 24);
4217
4218                 ctr.switch_value = 24;
4219                 ctr.info.id24 = &p24;
4220
4221                 result = cli_samr_set_userinfo(cli, mem_ctx, &user_pol, 24,
4222                                                &cli->user_session_key, &ctr);
4223
4224                 if (!NT_STATUS_IS_OK(result)) {
4225                         DEBUG(0,("Could not set trust account password: %s\n",
4226                                  nt_errstr(result)));
4227                         goto done;
4228                 }
4229         }
4230
4231  done:
4232         SAFE_FREE(acct_name);
4233         return result;
4234 }
4235
4236 /**
4237  * Create interdomain trust account for a remote domain.
4238  *
4239  * @param argc standard argc
4240  * @param argv standard argv without initial components
4241  *
4242  * @return Integer status (0 means success)
4243  **/
4244
4245 static int rpc_trustdom_add(int argc, const char **argv)
4246 {
4247         if (argc > 0) {
4248                 return run_rpc_command(NULL, PI_SAMR, 0, rpc_trustdom_add_internals,
4249                                        argc, argv);
4250         } else {
4251                 d_printf("Usage: net rpc trustdom add <domain>\n");
4252                 return -1;
4253         }
4254 }
4255
4256
4257 /**
4258  * Delete interdomain trust account for a remote domain.
4259  *
4260  * @param argc standard argc
4261  * @param argv standard argv without initial components
4262  *
4263  * @return Integer status (0 means success)
4264  **/
4265  
4266 static int rpc_trustdom_del(int argc, const char **argv)
4267 {
4268         d_printf("Sorry, not yet implemented.\n");
4269         d_printf("Use 'smbpasswd -x -i' instead.\n");
4270         return -1;
4271 }
4272
4273  
4274 /**
4275  * Establish trust relationship to a trusting domain.
4276  * Interdomain account must already be created on remote PDC.
4277  *
4278  * @param argc standard argc
4279  * @param argv standard argv without initial components
4280  *
4281  * @return Integer status (0 means success)
4282  **/
4283
4284 static int rpc_trustdom_establish(int argc, const char **argv)
4285 {
4286         struct cli_state *cli;
4287         struct in_addr server_ip;
4288         POLICY_HND connect_hnd;
4289         TALLOC_CTX *mem_ctx;
4290         NTSTATUS nt_status;
4291         DOM_SID *domain_sid;
4292         WKS_INFO_100 wks_info;
4293         
4294         char* domain_name;
4295         char* domain_name_pol;
4296         char* acct_name;
4297         fstring pdc_name;
4298
4299         /*
4300          * Connect to \\server\ipc$ as 'our domain' account with password
4301          */
4302
4303         if (argc != 1) {
4304                 d_printf("Usage: net rpc trustdom establish <domain_name>\n");
4305                 return -1;
4306         }
4307
4308         domain_name = smb_xstrdup(argv[0]);
4309         strupper_m(domain_name);
4310
4311         /* account name used at first is our domain's name with '$' */
4312         asprintf(&acct_name, "%s$", lp_workgroup());
4313         strupper_m(acct_name);
4314         
4315         /*
4316          * opt_workgroup will be used by connection functions further,
4317          * hence it should be set to remote domain name instead of ours
4318          */
4319         if (opt_workgroup) {
4320                 opt_workgroup = smb_xstrdup(domain_name);
4321         };
4322         
4323         opt_user_name = acct_name;
4324
4325         /* find the domain controller */
4326         if (!net_find_pdc(&server_ip, pdc_name, domain_name)) {
4327                 DEBUG(0, ("Couldn't find domain controller for domain %s\n", domain_name));
4328                 return -1;
4329         }
4330
4331         /* connect to ipc$ as username/password */
4332         nt_status = connect_to_ipc(&cli, &server_ip, pdc_name);
4333         if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
4334
4335                 /* Is it trusting domain account for sure ? */
4336                 DEBUG(0, ("Couldn't verify trusting domain account. Error was %s\n",
4337                         nt_errstr(nt_status)));
4338                 return -1;
4339         }
4340         
4341         /*
4342          * Connect to \\server\ipc$ again (this time anonymously)
4343          */
4344         
4345         nt_status = connect_to_ipc_anonymous(&cli, &server_ip, (char*)pdc_name);
4346         
4347         if (NT_STATUS_IS_ERR(nt_status)) {
4348                 DEBUG(0, ("Couldn't connect to domain %s controller. Error was %s.\n",
4349                         domain_name, nt_errstr(nt_status)));
4350         }
4351
4352         /*
4353          * Use NetServerEnum2 to make sure we're talking to a proper server
4354          */
4355          
4356         if (!cli_get_pdc_name(cli, domain_name, (char*)pdc_name)) {
4357                 DEBUG(0, ("NetServerEnum2 error: Couldn't find primary domain controller\
4358                          for domain %s\n", domain_name));
4359         }
4360          
4361         /*
4362          * Call WksQueryInfo to check remote server's capabilities
4363          * note: It is now used only to get unicode domain name
4364          */
4365         
4366         if (!cli_nt_session_open(cli, PI_WKSSVC)) {
4367                 DEBUG(0, ("Couldn't not initialise wkssvc pipe\n"));
4368                 return -1;
4369         }
4370
4371         if (!(mem_ctx = talloc_init("establishing trust relationship to domain %s",
4372                         domain_name))) {
4373                 DEBUG(0, ("talloc_init() failed\n"));
4374                 cli_shutdown(cli);
4375                 return -1;
4376         }
4377         
4378         nt_status = cli_wks_query_info(cli, mem_ctx, &wks_info);
4379         
4380         if (NT_STATUS_IS_ERR(nt_status)) {
4381                 DEBUG(0, ("WksQueryInfo call failed.\n"));
4382                 return -1;
4383         }
4384
4385         if (cli->nt_pipe_fnum)
4386                 cli_nt_session_close(cli);
4387
4388
4389         /*
4390          * Call LsaOpenPolicy and LsaQueryInfo
4391          */
4392          
4393         if (!(mem_ctx = talloc_init("rpc_trustdom_establish"))) {
4394                 DEBUG(0, ("talloc_init() failed\n"));
4395                 cli_shutdown(cli);
4396                 return -1;
4397         }
4398
4399         if (!cli_nt_session_open(cli, PI_LSARPC)) {
4400                 DEBUG(0, ("Could not initialise lsa pipe\n"));
4401                 cli_shutdown(cli);
4402                 return -1;
4403         }
4404
4405         nt_status = cli_lsa_open_policy2(cli, mem_ctx, True, SEC_RIGHTS_QUERY_VALUE,
4406                                          &connect_hnd);
4407         if (NT_STATUS_IS_ERR(nt_status)) {
4408                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
4409                         nt_errstr(nt_status)));
4410                 return -1;
4411         }
4412
4413         /* Querying info level 5 */
4414         
4415         nt_status = cli_lsa_query_info_policy(cli, mem_ctx, &connect_hnd,
4416                                               5 /* info level */, &domain_name_pol,
4417                                               &domain_sid);
4418         if (NT_STATUS_IS_ERR(nt_status)) {
4419                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
4420                         nt_errstr(nt_status)));
4421                 return -1;
4422         }
4423
4424
4425
4426
4427         /* There should be actually query info level 3 (following nt serv behaviour),
4428            but I still don't know if it's _really_ necessary */
4429                         
4430         /*
4431          * Store the password in secrets db
4432          */
4433
4434         if (!secrets_store_trusted_domain_password(domain_name, wks_info.uni_lan_grp.buffer,
4435                                                    wks_info.uni_lan_grp.uni_str_len, opt_password,
4436                                                    *domain_sid)) {
4437                 DEBUG(0, ("Storing password for trusted domain failed.\n"));
4438                 return -1;
4439         }
4440         
4441         /*
4442          * Close the pipes and clean up
4443          */
4444          
4445         nt_status = cli_lsa_close(cli, mem_ctx, &connect_hnd);
4446         if (NT_STATUS_IS_ERR(nt_status)) {
4447                 DEBUG(0, ("Couldn't close LSA pipe. Error was %s\n",
4448                         nt_errstr(nt_status)));
4449                 return -1;
4450         }
4451
4452         if (cli->nt_pipe_fnum)
4453                 cli_nt_session_close(cli);
4454          
4455         talloc_destroy(mem_ctx);
4456          
4457         d_printf("Trust to domain %s established\n", domain_name);
4458         return 0;
4459 }
4460
4461 /**
4462  * Revoke trust relationship to the remote domain
4463  *
4464  * @param argc standard argc
4465  * @param argv standard argv without initial components
4466  *
4467  * @return Integer status (0 means success)
4468  **/
4469
4470 static int rpc_trustdom_revoke(int argc, const char **argv)
4471 {
4472         char* domain_name;
4473
4474         if (argc < 1) return -1;
4475         
4476         /* generate upper cased domain name */
4477         domain_name = smb_xstrdup(argv[0]);
4478         strupper_m(domain_name);
4479
4480         /* delete password of the trust */
4481         if (!trusted_domain_password_delete(domain_name)) {
4482                 DEBUG(0, ("Failed to revoke relationship to the trusted domain %s\n",
4483                           domain_name));
4484                 return -1;
4485         };
4486         
4487         return 0;
4488 }
4489
4490 /**
4491  * Usage for 'net rpc trustdom' command
4492  *
4493  * @param argc standard argc
4494  * @param argv standard argv without inital components
4495  *
4496  * @return Integer status returned to shell
4497  **/
4498  
4499 static int rpc_trustdom_usage(int argc, const char **argv)
4500 {
4501         d_printf("  net rpc trustdom add \t\t add trusting domain's account\n");
4502         d_printf("  net rpc trustdom del \t\t delete trusting domain's account\n");
4503         d_printf("  net rpc trustdom establish \t establish relationship to trusted domain\n");
4504         d_printf("  net rpc trustdom revoke \t abandon relationship to trusted domain\n");
4505         d_printf("  net rpc trustdom list \t show current interdomain trust relationships\n");
4506         return -1;
4507 }
4508
4509
4510 static NTSTATUS rpc_query_domain_sid(const DOM_SID *domain_sid, 
4511                                      const char *domain_name, 
4512                                      struct cli_state *cli, TALLOC_CTX *mem_ctx,
4513                                      int argc, const char **argv)
4514 {
4515         fstring str_sid;
4516         sid_to_string(str_sid, domain_sid);
4517         d_printf("%s\n", str_sid);
4518         return NT_STATUS_OK;
4519 }
4520
4521
4522 static int rpc_trustdom_list(int argc, const char **argv)
4523 {
4524         /* common variables */
4525         TALLOC_CTX* mem_ctx;
4526         struct cli_state *cli, *remote_cli;
4527         NTSTATUS nt_status;
4528         const char *domain_name = NULL;
4529         DOM_SID *queried_dom_sid;
4530         fstring ascii_sid, padding;
4531         int ascii_dom_name_len;
4532         POLICY_HND connect_hnd;
4533         
4534         /* trusted domains listing variables */
4535         unsigned int num_domains, enum_ctx = 0;
4536         int i, pad_len, col_len = 20;
4537         DOM_SID *domain_sids;
4538         char **trusted_dom_names;
4539         fstring pdc_name;
4540         char *dummy;
4541         
4542         /* trusting domains listing variables */
4543         POLICY_HND domain_hnd;
4544         char **trusting_dom_names;
4545         uint32 *trusting_dom_rids;
4546         
4547         /*
4548          * Listing trusted domains (stored in secrets.tdb, if local)
4549          */
4550
4551         mem_ctx = talloc_init("trust relationships listing");
4552
4553         /*
4554          * set domain and pdc name to local samba server (default)
4555          * or to remote one given in command line
4556          */
4557         
4558         if (StrCaseCmp(opt_workgroup, lp_workgroup())) {
4559                 domain_name = opt_workgroup;
4560                 opt_target_workgroup = opt_workgroup;
4561         } else {
4562                 fstrcpy(pdc_name, global_myname());
4563                 domain_name = talloc_strdup(mem_ctx, lp_workgroup());
4564                 opt_target_workgroup = domain_name;
4565         };
4566
4567         /* open \PIPE\lsarpc and open policy handle */
4568         if (!(cli = net_make_ipc_connection(NET_FLAGS_PDC))) {
4569                 DEBUG(0, ("Couldn't connect to domain controller\n"));
4570                 return -1;
4571         };
4572
4573         if (!cli_nt_session_open(cli, PI_LSARPC)) {
4574                 DEBUG(0, ("Could not initialise lsa pipe\n"));
4575                 return -1;
4576         };
4577
4578         nt_status = cli_lsa_open_policy2(cli, mem_ctx, False, SEC_RIGHTS_QUERY_VALUE,
4579                                         &connect_hnd);
4580         if (NT_STATUS_IS_ERR(nt_status)) {
4581                 DEBUG(0, ("Couldn't open policy handle. Error was %s\n",
4582                         nt_errstr(nt_status)));
4583                 return -1;
4584         };
4585         
4586         /* query info level 5 to obtain sid of a domain being queried */
4587         nt_status = cli_lsa_query_info_policy(
4588                 cli, mem_ctx, &connect_hnd, 5 /* info level */, 
4589                 &dummy, &queried_dom_sid);
4590
4591         if (NT_STATUS_IS_ERR(nt_status)) {
4592                 DEBUG(0, ("LSA Query Info failed. Returned error was %s\n",
4593                         nt_errstr(nt_status)));
4594                 return -1;
4595         }
4596                 
4597         /*
4598          * Keep calling LsaEnumTrustdom over opened pipe until
4599          * the end of enumeration is reached
4600          */
4601          
4602         d_printf("Trusted domains list:\n\n");
4603
4604         do {
4605                 nt_status = cli_lsa_enum_trust_dom(cli, mem_ctx, &connect_hnd, &enum_ctx,
4606                                                    &num_domains,
4607                                                    &trusted_dom_names, &domain_sids);
4608                 
4609                 if (NT_STATUS_IS_ERR(nt_status)) {
4610                         DEBUG(0, ("Couldn't enumerate trusted domains. Error was %s\n",
4611                                 nt_errstr(nt_status)));
4612                         return -1;
4613                 };
4614                 
4615                 for (i = 0; i < num_domains; i++) {
4616                         /* convert sid into ascii string */
4617                         sid_to_string(ascii_sid, &(domain_sids[i]));
4618                 
4619                         /* calculate padding space for d_printf to look nicer */
4620                         pad_len = col_len - strlen(trusted_dom_names[i]);
4621                         padding[pad_len] = 0;
4622                         do padding[--pad_len] = ' '; while (pad_len);
4623                         
4624                         d_printf("%s%s%s\n", trusted_dom_names[i], padding, ascii_sid);
4625                 };
4626                 
4627                 /*
4628                  * in case of no trusted domains say something rather
4629                  * than just display blank line
4630                  */
4631                 if (!num_domains) d_printf("none\n");
4632
4633         } while (NT_STATUS_EQUAL(nt_status, STATUS_MORE_ENTRIES));
4634
4635         /* close this connection before doing next one */
4636         nt_status = cli_lsa_close(cli, mem_ctx, &connect_hnd);
4637         if (NT_STATUS_IS_ERR(nt_status)) {
4638                 DEBUG(0, ("Couldn't properly close lsa policy handle. Error was %s\n",
4639                         nt_errstr(nt_status)));
4640                 return -1;
4641         };
4642         
4643         cli_nt_session_close(cli);
4644
4645         /*
4646          * Listing trusting domains (stored in passdb backend, if local)
4647          */
4648         
4649         d_printf("\nTrusting domains list:\n\n");
4650
4651         /*
4652          * Open \PIPE\samr and get needed policy handles
4653          */
4654         if (!cli_nt_session_open(cli, PI_SAMR)) {
4655                 DEBUG(0, ("Could not initialise samr pipe\n"));
4656                 return -1;
4657         };
4658         
4659         /* SamrConnect */
4660         nt_status = cli_samr_connect(cli, mem_ctx, SA_RIGHT_SAM_OPEN_DOMAIN,
4661                                                                  &connect_hnd);
4662         if (!NT_STATUS_IS_OK(nt_status)) {
4663                 DEBUG(0, ("Couldn't open SAMR policy handle. Error was %s\n",
4664                         nt_errstr(nt_status)));
4665                 return -1;
4666         };
4667         
4668         /* SamrOpenDomain - we have to open domain policy handle in order to be
4669            able to enumerate accounts*/
4670         nt_status = cli_samr_open_domain(cli, mem_ctx, &connect_hnd,
4671                                          SA_RIGHT_DOMAIN_ENUM_ACCOUNTS,
4672                                          queried_dom_sid, &domain_hnd);                                                                  
4673         if (!NT_STATUS_IS_OK(nt_status)) {
4674                 DEBUG(0, ("Couldn't open domain object. Error was %s\n",
4675                         nt_errstr(nt_status)));
4676                 return -1;
4677         };
4678         
4679         /*
4680          * perform actual enumeration
4681          */
4682          
4683         enum_ctx = 0;   /* reset enumeration context from last enumeration */
4684         do {
4685                         
4686                 nt_status = cli_samr_enum_dom_users(cli, mem_ctx, &domain_hnd,
4687                                                     &enum_ctx, ACB_DOMTRUST, 0xffff,
4688                                                     &trusting_dom_names, &trusting_dom_rids,
4689                                                     &num_domains);
4690                 if (NT_STATUS_IS_ERR(nt_status)) {
4691                         DEBUG(0, ("Couldn't enumerate accounts. Error was: %s\n",
4692                                 nt_errstr(nt_status)));
4693                         return -1;
4694                 };
4695                 
4696                 for (i = 0; i < num_domains; i++) {
4697
4698                         /*
4699                          * get each single domain's sid (do we _really_ need this ?):
4700                          *  1) connect to domain's pdc
4701                          *  2) query the pdc for domain's sid
4702                          */
4703
4704                         /* get rid of '$' tail */
4705                         ascii_dom_name_len = strlen(trusting_dom_names[i]);
4706                         if (ascii_dom_name_len && ascii_dom_name_len < FSTRING_LEN)
4707                                 trusting_dom_names[i][ascii_dom_name_len - 1] = '\0';
4708                         
4709                         /* calculate padding space for d_printf to look nicer */
4710                         pad_len = col_len - strlen(trusting_dom_names[i]);
4711                         padding[pad_len] = 0;
4712                         do padding[--pad_len] = ' '; while (pad_len);
4713
4714                         /* set opt_* variables to remote domain */
4715                         strupper_m(trusting_dom_names[i]);
4716                         opt_workgroup = talloc_strdup(mem_ctx, trusting_dom_names[i]);
4717                         opt_target_workgroup = opt_workgroup;
4718                         
4719                         d_printf("%s%s", trusting_dom_names[i], padding);
4720                         
4721                         /* connect to remote domain controller */
4722                         remote_cli = net_make_ipc_connection(NET_FLAGS_PDC | NET_FLAGS_ANONYMOUS);
4723                         if (remote_cli) {                       
4724                                 /* query for domain's sid */
4725                                 if (run_rpc_command(remote_cli, PI_LSARPC, 0, rpc_query_domain_sid, argc, argv))
4726                                         d_printf("couldn't get domain's sid\n");
4727
4728                                 cli_shutdown(remote_cli);
4729                         
4730                         } else {
4731                                 d_printf("domain controller is not responding\n");
4732                         };
4733                 };
4734                 
4735                 if (!num_domains) d_printf("none\n");
4736                 
4737         } while (NT_STATUS_EQUAL(nt_status, STATUS_MORE_ENTRIES));
4738
4739         /* close opened samr and domain policy handles */
4740         nt_status = cli_samr_close(cli, mem_ctx, &domain_hnd);
4741         if (!NT_STATUS_IS_OK(nt_status)) {
4742                 DEBUG(0, ("Couldn't properly close domain policy handle for domain %s\n", domain_name));
4743         };
4744         
4745         nt_status = cli_samr_close(cli, mem_ctx, &connect_hnd);
4746         if (!NT_STATUS_IS_OK(nt_status)) {
4747                 DEBUG(0, ("Couldn't properly close samr policy handle for domain %s\n", domain_name));
4748         };
4749         
4750         /* close samr pipe and connection to IPC$ */
4751         cli_nt_session_close(cli);
4752         cli_shutdown(cli);
4753
4754         talloc_destroy(mem_ctx);         
4755         return 0;
4756 }
4757
4758 /**
4759  * Entrypoint for 'net rpc trustdom' code
4760  *
4761  * @param argc standard argc
4762  * @param argv standard argv without initial components
4763  *
4764  * @return Integer status (0 means success)
4765  */
4766
4767 static int rpc_trustdom(int argc, const char **argv)
4768 {
4769         struct functable func[] = {
4770                 {"add", rpc_trustdom_add},
4771                 {"del", rpc_trustdom_del},
4772                 {"establish", rpc_trustdom_establish},
4773                 {"revoke", rpc_trustdom_revoke},
4774                 {"help", rpc_trustdom_usage},
4775                 {"list", rpc_trustdom_list},
4776                 {NULL, NULL}
4777         };
4778
4779         if (argc == 0) {
4780                 rpc_trustdom_usage(argc, argv);
4781                 return -1;
4782         }
4783
4784         return (net_run_function(argc, argv, func, rpc_user_usage));
4785 }
4786
4787 /**
4788  * Check if a server will take rpc commands
4789  * @param flags Type of server to connect to (PDC, DMB, localhost)
4790  *              if the host is not explicitly specified
4791  * @return  BOOL (true means rpc supported)
4792  */
4793 BOOL net_rpc_check(unsigned flags)
4794 {
4795         struct cli_state cli;
4796         BOOL ret = False;
4797         struct in_addr server_ip;
4798         char *server_name = NULL;
4799
4800         /* flags (i.e. server type) may depend on command */
4801         if (!net_find_server(flags, &server_ip, &server_name))
4802                 return False;
4803
4804         ZERO_STRUCT(cli);
4805         if (cli_initialise(&cli) == False)
4806                 return False;
4807
4808         if (!cli_connect(&cli, server_name, &server_ip))
4809                 goto done;
4810         if (!attempt_netbios_session_request(&cli, global_myname(), 
4811                                              server_name, &server_ip))
4812                 goto done;
4813         if (!cli_negprot(&cli))
4814                 goto done;
4815         if (cli.protocol < PROTOCOL_NT1)
4816                 goto done;
4817
4818         ret = True;
4819  done:
4820         cli_shutdown(&cli);
4821         return ret;
4822 }
4823
4824 /* dump sam database via samsync rpc calls */
4825 static int rpc_samdump(int argc, const char **argv) {
4826         return run_rpc_command(NULL, PI_NETLOGON, NET_FLAGS_ANONYMOUS, rpc_samdump_internals,
4827                                argc, argv);
4828 }
4829
4830 /* syncronise sam database via samsync rpc calls */
4831 static int rpc_vampire(int argc, const char **argv) {
4832         return run_rpc_command(NULL, PI_NETLOGON, NET_FLAGS_ANONYMOUS, rpc_vampire_internals,
4833                                argc, argv);
4834 }
4835
4836 /** 
4837  * Migrate everything from a print-server
4838  *
4839  * @param argc  Standard main() style argc
4840  * @param argv  Standard main() style argv.  Initial components are already
4841  *              stripped
4842  *
4843  * @return A shell status integer (0 for success)
4844  *
4845  * The order is important !
4846  * To successfully add drivers the print-queues have to exist !
4847  * Applying ACLs should be the last step, because you're easily locked out
4848  *
4849  **/
4850 static int rpc_printer_migrate_all(int argc, const char **argv)
4851 {
4852         int ret;
4853
4854         if (!opt_host) {
4855                 printf("no server to migrate\n");
4856                 return -1;
4857         }
4858
4859         ret = run_rpc_command(NULL, PI_SPOOLSS, 0, rpc_printer_migrate_printers_internals, argc, argv);
4860         if (ret)
4861                 return ret;
4862
4863         ret = run_rpc_command(NULL, PI_SPOOLSS, 0, rpc_printer_migrate_drivers_internals, argc, argv);
4864         if (ret)
4865                 return ret;
4866
4867         ret = run_rpc_command(NULL, PI_SPOOLSS, 0, rpc_printer_migrate_forms_internals, argc, argv);
4868         if (ret)
4869                 return ret;
4870
4871         ret = run_rpc_command(NULL, PI_SPOOLSS, 0, rpc_printer_migrate_settings_internals, argc, argv);
4872         if (ret)
4873                 return ret;
4874
4875         return run_rpc_command(NULL, PI_SPOOLSS, 0, rpc_printer_migrate_security_internals, argc, argv);
4876
4877 }
4878
4879 /** 
4880  * Migrate print-drivers from a print-server
4881  *
4882  * @param argc  Standard main() style argc
4883  * @param argv  Standard main() style argv.  Initial components are already
4884  *              stripped
4885  *
4886  * @return A shell status integer (0 for success)
4887  **/
4888 static int rpc_printer_migrate_drivers(int argc, const char **argv)
4889 {
4890         if (!opt_host) {
4891                 printf("no server to migrate\n");
4892                 return -1;
4893         }
4894
4895         return run_rpc_command(NULL, PI_SPOOLSS, 0, 
4896                                rpc_printer_migrate_drivers_internals,
4897                                argc, argv);
4898 }
4899
4900 /** 
4901  * Migrate print-forms from a print-server
4902  *
4903  * @param argc  Standard main() style argc
4904  * @param argv  Standard main() style argv.  Initial components are already
4905  *              stripped
4906  *
4907  * @return A shell status integer (0 for success)
4908  **/
4909 static int rpc_printer_migrate_forms(int argc, const char **argv)
4910 {
4911         if (!opt_host) {
4912                 printf("no server to migrate\n");
4913                 return -1;
4914         }
4915
4916         return run_rpc_command(NULL, PI_SPOOLSS, 0, 
4917                                rpc_printer_migrate_forms_internals,
4918                                argc, argv);
4919 }
4920
4921 /** 
4922  * Migrate printers from a print-server
4923  *
4924  * @param argc  Standard main() style argc
4925  * @param argv  Standard main() style argv.  Initial components are already
4926  *              stripped
4927  *
4928  * @return A shell status integer (0 for success)
4929  **/
4930 static int rpc_printer_migrate_printers(int argc, const char **argv)
4931 {
4932         if (!opt_host) {
4933                 printf("no server to migrate\n");
4934                 return -1;
4935         }
4936
4937         return run_rpc_command(NULL, PI_SPOOLSS, 0, 
4938                                rpc_printer_migrate_printers_internals,
4939                                argc, argv);
4940 }
4941
4942 /** 
4943  * Migrate printer-ACLs from a print-server
4944  *
4945  * @param argc  Standard main() style argc
4946  * @param argv  Standard main() style argv.  Initial components are already
4947  *              stripped
4948  *
4949  * @return A shell status integer (0 for success)
4950  **/
4951 static int rpc_printer_migrate_security(int argc, const char **argv)
4952 {
4953         if (!opt_host) {
4954                 printf("no server to migrate\n");
4955                 return -1;
4956         }
4957
4958         return run_rpc_command(NULL, PI_SPOOLSS, 0, 
4959                                rpc_printer_migrate_security_internals,
4960                                argc, argv);
4961 }
4962
4963 /** 
4964  * Migrate printer-settings from a print-server
4965  *
4966  * @param argc  Standard main() style argc
4967  * @param argv  Standard main() style argv.  Initial components are already
4968  *              stripped
4969  *
4970  * @return A shell status integer (0 for success)
4971  **/
4972 static int rpc_printer_migrate_settings(int argc, const char **argv)
4973 {
4974         if (!opt_host) {
4975                 printf("no server to migrate\n");
4976                 return -1;
4977         }
4978
4979         return run_rpc_command(NULL, PI_SPOOLSS, 0, 
4980                                rpc_printer_migrate_settings_internals,
4981                                argc, argv);
4982 }
4983
4984 /** 
4985  * 'net rpc printer' entrypoint.
4986  * @param argc  Standard main() style argc
4987  * @param argv  Standard main() style argv.  Initial components are already
4988  *              stripped
4989  **/
4990
4991 int rpc_printer_migrate(int argc, const char **argv) 
4992 {
4993
4994         /* ouch: when addriver and setdriver are called from within
4995            rpc_printer_migrate_drivers_internals, the printer-queue already
4996            *has* to exist */
4997
4998         struct functable func[] = {
4999                 {"all",         rpc_printer_migrate_all},
5000                 {"drivers",     rpc_printer_migrate_drivers},
5001                 {"forms",       rpc_printer_migrate_forms},
5002                 {"help",        rpc_printer_usage},
5003                 {"printers",    rpc_printer_migrate_printers},
5004                 {"security",    rpc_printer_migrate_security},
5005                 {"settings",    rpc_printer_migrate_settings},
5006                 {NULL, NULL}
5007         };
5008
5009         return net_run_function(argc, argv, func, rpc_printer_usage);
5010 }
5011
5012
5013 /** 
5014  * List printers on a remote RPC server
5015  *
5016  * @param argc  Standard main() style argc
5017  * @param argv  Standard main() style argv.  Initial components are already
5018  *              stripped
5019  *
5020  * @return A shell status integer (0 for success)
5021  **/
5022 static int rpc_printer_list(int argc, const char **argv)
5023 {
5024
5025         return run_rpc_command(NULL, PI_SPOOLSS, 0, 
5026                                rpc_printer_list_internals,
5027                                argc, argv);
5028 }
5029
5030 /** 
5031  * List printer-drivers on a remote RPC server
5032  *
5033  * @param argc  Standard main() style argc
5034  * @param argv  Standard main() style argv.  Initial components are already
5035  *              stripped
5036  *
5037  * @return A shell status integer (0 for success)
5038  **/
5039 static int rpc_printer_driver_list(int argc, const char **argv)
5040 {
5041
5042         return run_rpc_command(NULL, PI_SPOOLSS, 0, 
5043                                rpc_printer_driver_list_internals,
5044                                argc, argv);
5045 }
5046
5047 /** 
5048  * Display rpc printer help page.
5049  * @param argc  Standard main() style argc
5050  * @param argv  Standard main() style argv.  Initial components are already
5051  *              stripped
5052  **/
5053 int rpc_printer_usage(int argc, const char **argv)
5054 {
5055         return net_help_printer(argc, argv);
5056 }
5057
5058 /** 
5059  * 'net rpc printer' entrypoint.
5060  * @param argc  Standard main() style argc
5061  * @param argv  Standard main() style argv.  Initial components are already
5062  *              stripped
5063  **/
5064 int net_rpc_printer(int argc, const char **argv) 
5065 {
5066         struct functable func[] = {
5067                 {"list", rpc_printer_list},
5068                 {"migrate", rpc_printer_migrate},
5069                 {"driver", rpc_printer_driver_list},
5070                 {NULL, NULL}
5071         };
5072
5073         if (argc == 0)
5074                 return run_rpc_command(NULL, PI_SPOOLSS, 0, 
5075                                rpc_printer_list_internals,
5076                                argc, argv);
5077
5078         return net_run_function(argc, argv, func, rpc_printer_usage);
5079 }
5080
5081 /****************************************************************************/
5082
5083
5084 /** 
5085  * Basic usage function for 'net rpc'
5086  * @param argc  Standard main() style argc
5087  * @param argv  Standard main() style argv.  Initial components are already
5088  *              stripped
5089  **/
5090
5091 int net_rpc_usage(int argc, const char **argv) 
5092 {
5093         d_printf("  net rpc info \t\t\tshow basic info about a domain \n");
5094         d_printf("  net rpc join \t\t\tto join a domain \n");
5095         d_printf("  net rpc oldjoin \t\t\tto join a domain created in server manager\n\n\n");
5096         d_printf("  net rpc testjoin \t\ttests that a join is valid\n");
5097         d_printf("  net rpc user \t\t\tto add, delete and list users\n");
5098         d_printf("  net rpc password <username> [<password>] -Uadmin_username%%admin_pass\n");
5099         d_printf("  net rpc group \t\tto list groups\n");
5100         d_printf("  net rpc share \t\tto add, delete, list and migrate shares\n");
5101         d_printf("  net rpc printer \t\tto list and migrate printers\n");
5102         d_printf("  net rpc file \t\t\tto list open files\n");
5103         d_printf("  net rpc changetrustpw \tto change the trust account password\n");
5104         d_printf("  net rpc getsid \t\tfetch the domain sid into the local secrets.tdb\n");
5105         d_printf("  net rpc vampire \t\tsyncronise an NT PDC's users and groups into the local passdb\n");
5106         d_printf("  net rpc samdump \t\tdiplay an NT PDC's users, groups and other data\n");
5107         d_printf("  net rpc trustdom \t\tto create trusting domain's account\n"
5108                  "\t\t\t\t\tor establish trust\n");
5109         d_printf("  net rpc abortshutdown \tto abort the shutdown of a remote server\n");
5110         d_printf("  net rpc shutdown \t\tto shutdown a remote server\n");
5111         d_printf("\n");
5112         d_printf("'net rpc shutdown' also accepts the following miscellaneous options:\n"); /* misc options */
5113         d_printf("\t-r or --reboot\trequest remote server reboot on shutdown\n");
5114         d_printf("\t-f or --force\trequest the remote server force its shutdown\n");
5115         d_printf("\t-t or --timeout=<timeout>\tnumber of seconds before shutdown\n");
5116         d_printf("\t-c or --comment=<message>\ttext message to display on impending shutdown\n");
5117         return -1;
5118 }
5119
5120
5121 /**
5122  * Help function for 'net rpc'.  Calls command specific help if requested
5123  * or displays usage of net rpc
5124  * @param argc  Standard main() style argc
5125  * @param argv  Standard main() style argv.  Initial components are already
5126  *              stripped
5127  **/
5128
5129 int net_rpc_help(int argc, const char **argv)
5130 {
5131         struct functable func[] = {
5132                 {"join", rpc_join_usage},
5133                 {"user", rpc_user_usage},
5134                 {"group", rpc_group_usage},
5135                 {"share", rpc_share_usage},
5136                 /*{"changetrustpw", rpc_changetrustpw_usage}, */
5137                 {"trustdom", rpc_trustdom_usage},
5138                 /*{"abortshutdown", rpc_shutdown_abort_usage},*/
5139                 /*{"shutdown", rpc_shutdown_usage}, */
5140                 {NULL, NULL}
5141         };
5142
5143         if (argc == 0) {
5144                 net_rpc_usage(argc, argv);
5145                 return -1;
5146         }
5147
5148         return (net_run_function(argc, argv, func, rpc_user_usage));
5149 }
5150
5151
5152 /** 
5153  * 'net rpc' entrypoint.
5154  * @param argc  Standard main() style argc
5155  * @param argv  Standard main() style argv.  Initial components are already
5156  *              stripped
5157  **/
5158
5159 int net_rpc(int argc, const char **argv)
5160 {
5161         struct functable func[] = {
5162                 {"info", net_rpc_info},
5163                 {"join", net_rpc_join},
5164                 {"oldjoin", net_rpc_oldjoin},
5165                 {"testjoin", net_rpc_testjoin},
5166                 {"user", net_rpc_user},
5167                 {"password", rpc_user_password},
5168                 {"group", net_rpc_group},
5169                 {"share", net_rpc_share},
5170                 {"file", net_rpc_file},
5171                 {"printer", net_rpc_printer},
5172                 {"changetrustpw", net_rpc_changetrustpw},
5173                 {"trustdom", rpc_trustdom},
5174                 {"abortshutdown", rpc_shutdown_abort},
5175                 {"shutdown", rpc_shutdown},
5176                 {"samdump", rpc_samdump},
5177                 {"vampire", rpc_vampire},
5178                 {"getsid", net_rpc_getsid},
5179                 {"help", net_rpc_help},
5180                 {NULL, NULL}
5181         };
5182         return net_run_function(argc, argv, func, net_rpc_usage);
5183 }