Merge commit 'origin/v3-2-test' into my_branch
[ira/wip.git] / source3 / utils / net.c
1 /* 
2    Samba Unix/Linux SMB client library 
3    Distributed SMB/CIFS Server Management Utility 
4    Copyright (C) 2001 Steve French  (sfrench@us.ibm.com)
5    Copyright (C) 2001 Jim McDonough (jmcd@us.ibm.com)
6    Copyright (C) 2001 Andrew Tridgell (tridge@samba.org)
7    Copyright (C) 2001 Andrew Bartlett (abartlet@samba.org)
8
9    Originally written by Steve and Jim. Largely rewritten by tridge in
10    November 2001.
11
12    Reworked again by abartlet in December 2001
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18    
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23    
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26  
27 /*****************************************************/
28 /*                                                   */
29 /*   Distributed SMB/CIFS Server Management Utility  */
30 /*                                                   */
31 /*   The intent was to make the syntax similar       */
32 /*   to the NET utility (first developed in DOS      */
33 /*   with additional interesting & useful functions  */
34 /*   added in later SMB server network operating     */
35 /*   systems).                                       */
36 /*                                                   */
37 /*****************************************************/
38
39 #include "includes.h"
40 #include "utils/net.h"
41
42 /***********************************************************************/
43 /* Beginning of internationalization section.  Translatable constants  */
44 /* should be kept in this area and referenced in the rest of the code. */
45 /*                                                                     */
46 /* No functions, outside of Samba or LSB (Linux Standards Base) should */
47 /* be used (if possible).                                              */
48 /***********************************************************************/
49
50 #define YES_STRING              "Yes"
51 #define NO_STRING               "No"
52
53 /************************************************************************************/
54 /*                       end of internationalization section                        */
55 /************************************************************************************/
56
57 /* Yes, these buggers are globals.... */
58 const char *opt_requester_name = NULL;
59 const char *opt_host = NULL; 
60 const char *opt_password = NULL;
61 const char *opt_user_name = NULL;
62 BOOL opt_user_specified = False;
63 const char *opt_workgroup = NULL;
64 int opt_long_list_entries = 0;
65 int opt_reboot = 0;
66 int opt_force = 0;
67 int opt_stdin = 0;
68 int opt_port = 0;
69 int opt_verbose = 0;
70 int opt_maxusers = -1;
71 const char *opt_comment = "";
72 const char *opt_container = NULL;
73 int opt_flags = -1;
74 int opt_timeout = 0;
75 const char *opt_target_workgroup = NULL;
76 int opt_machine_pass = 0;
77 BOOL opt_localgroup = False;
78 BOOL opt_domaingroup = False;
79 static BOOL do_talloc_report=False;
80 const char *opt_newntname = "";
81 int opt_rid = 0;
82 int opt_acls = 0;
83 int opt_attrs = 0;
84 int opt_timestamps = 0;
85 const char *opt_exclude = NULL;
86 const char *opt_destination = NULL;
87 BOOL opt_testmode = False;
88
89 BOOL opt_have_ip = False;
90 struct in_addr opt_dest_ip;
91
92 extern BOOL AllowDebugChange;
93
94 uint32 get_sec_channel_type(const char *param) 
95 {
96         if (!(param && *param)) {
97                 return get_default_sec_channel();
98         } else {
99                 if (strequal(param, "PDC")) {
100                         return SEC_CHAN_BDC;
101                 } else if (strequal(param, "BDC")) {
102                         return SEC_CHAN_BDC;
103                 } else if (strequal(param, "MEMBER")) {
104                         return SEC_CHAN_WKSTA;
105 #if 0                   
106                 } else if (strequal(param, "DOMAIN")) {
107                         return SEC_CHAN_DOMAIN;
108 #endif
109                 } else {
110                         return get_default_sec_channel();
111                 }
112         }
113 }
114
115 /*
116   run a function from a function table. If not found then
117   call the specified usage function 
118 */
119 int net_run_function(int argc, const char **argv, struct functable *table, 
120                      int (*usage_fn)(int argc, const char **argv))
121 {
122         int i;
123         
124         if (argc < 1) {
125                 d_printf("\nUsage: \n");
126                 return usage_fn(argc, argv);
127         }
128         for (i=0; table[i].funcname; i++) {
129                 if (StrCaseCmp(argv[0], table[i].funcname) == 0)
130                         return table[i].fn(argc-1, argv+1);
131         }
132         d_fprintf(stderr, "No command: %s\n", argv[0]);
133         return usage_fn(argc, argv);
134 }
135
136 /*
137  * run a function from a function table.
138  */
139 int net_run_function2(int argc, const char **argv, const char *whoami,
140                       struct functable2 *table)
141 {
142         int i;
143
144         if (argc != 0) {
145                 for (i=0; table[i].funcname; i++) {
146                         if (StrCaseCmp(argv[0], table[i].funcname) == 0)
147                                 return table[i].fn(argc-1, argv+1);
148                 }
149         }
150
151         for (i=0; table[i].funcname != NULL; i++) {
152                 d_printf("%s %-15s %s\n", whoami, table[i].funcname,
153                          table[i].helptext);
154         }
155
156         return -1;
157 }
158
159 /****************************************************************************
160 connect to \\server\service 
161 ****************************************************************************/
162
163 NTSTATUS connect_to_service(struct cli_state **c, struct in_addr *server_ip,
164                                         const char *server_name, 
165                                         const char *service_name, 
166                                         const char *service_type)
167 {
168         NTSTATUS nt_status;
169
170         opt_password = net_prompt_pass(opt_user_name);
171         if (!opt_password) {
172                 return NT_STATUS_NO_MEMORY;
173         }
174
175         nt_status = cli_full_connection(c, NULL, server_name, 
176                                         server_ip, opt_port,
177                                         service_name, service_type,  
178                                         opt_user_name, opt_workgroup,
179                                         opt_password, 0, Undefined, NULL);
180         if (NT_STATUS_IS_OK(nt_status)) {
181                 return nt_status;
182         } else {
183                 d_fprintf(stderr, "Could not connect to server %s\n", server_name);
184
185                 /* Display a nicer message depending on the result */
186
187                 if (NT_STATUS_V(nt_status) == 
188                     NT_STATUS_V(NT_STATUS_LOGON_FAILURE))
189                         d_fprintf(stderr, "The username or password was not correct.\n");
190
191                 if (NT_STATUS_V(nt_status) == 
192                     NT_STATUS_V(NT_STATUS_ACCOUNT_LOCKED_OUT))
193                         d_fprintf(stderr, "The account was locked out.\n");
194
195                 if (NT_STATUS_V(nt_status) == 
196                     NT_STATUS_V(NT_STATUS_ACCOUNT_DISABLED))
197                         d_fprintf(stderr, "The account was disabled.\n");
198
199                 return nt_status;
200         }
201 }
202
203
204 /****************************************************************************
205 connect to \\server\ipc$  
206 ****************************************************************************/
207 NTSTATUS connect_to_ipc(struct cli_state **c, struct in_addr *server_ip,
208                                         const char *server_name)
209 {
210         return connect_to_service(c, server_ip, server_name, "IPC$", "IPC");
211 }
212
213 /****************************************************************************
214 connect to \\server\ipc$ anonymously
215 ****************************************************************************/
216 NTSTATUS connect_to_ipc_anonymous(struct cli_state **c,
217                         struct in_addr *server_ip, const char *server_name)
218 {
219         NTSTATUS nt_status;
220
221         nt_status = cli_full_connection(c, opt_requester_name, server_name, 
222                                         server_ip, opt_port,
223                                         "IPC$", "IPC",  
224                                         "", "",
225                                         "", 0, Undefined, NULL);
226         
227         if (NT_STATUS_IS_OK(nt_status)) {
228                 return nt_status;
229         } else {
230                 DEBUG(1,("Cannot connect to server (anonymously).  Error was %s\n", nt_errstr(nt_status)));
231                 return nt_status;
232         }
233 }
234
235 /****************************************************************************
236  Return malloced user@realm for krb5 login.
237 ****************************************************************************/
238
239 static char *get_user_and_realm(const char *username)
240 {
241         char *user_and_realm = NULL;
242
243         if (!username) {
244                 return NULL;
245         }
246         if (strchr_m(username, '@')) {
247                 user_and_realm = SMB_STRDUP(username);
248         } else {
249                 if (asprintf(&user_and_realm, "%s@%s", username, lp_realm()) == -1) {
250                         user_and_realm = NULL;
251                 }
252         }
253         return user_and_realm;
254 }
255
256 /****************************************************************************
257 connect to \\server\ipc$ using KRB5
258 ****************************************************************************/
259
260 NTSTATUS connect_to_ipc_krb5(struct cli_state **c,
261                         struct in_addr *server_ip, const char *server_name)
262 {
263         NTSTATUS nt_status;
264         char *user_and_realm = NULL;
265
266         opt_password = net_prompt_pass(opt_user_name);
267         if (!opt_password) {
268                 return NT_STATUS_NO_MEMORY;
269         }
270
271         user_and_realm = get_user_and_realm(opt_user_name);
272         if (!user_and_realm) {
273                 return NT_STATUS_NO_MEMORY;
274         }
275
276         nt_status = cli_full_connection(c, NULL, server_name, 
277                                         server_ip, opt_port,
278                                         "IPC$", "IPC",  
279                                         user_and_realm, opt_workgroup,
280                                         opt_password, CLI_FULL_CONNECTION_USE_KERBEROS, 
281                                         Undefined, NULL);
282         
283         SAFE_FREE(user_and_realm);
284
285         if (NT_STATUS_IS_OK(nt_status)) {
286                 return nt_status;
287         } else {
288                 DEBUG(1,("Cannot connect to server using kerberos.  Error was %s\n", nt_errstr(nt_status)));
289                 return nt_status;
290         }
291 }
292
293 /**
294  * Connect a server and open a given pipe
295  *
296  * @param cli_dst               A cli_state 
297  * @param pipe                  The pipe to open
298  * @param got_pipe              boolean that stores if we got a pipe
299  *
300  * @return Normal NTSTATUS return.
301  **/
302 NTSTATUS connect_dst_pipe(struct cli_state **cli_dst, struct rpc_pipe_client **pp_pipe_hnd, int pipe_num)
303 {
304         NTSTATUS nt_status;
305         char *server_name = SMB_STRDUP("127.0.0.1");
306         struct cli_state *cli_tmp = NULL;
307         struct rpc_pipe_client *pipe_hnd = NULL;
308
309         if (server_name == NULL) {
310                 return NT_STATUS_NO_MEMORY;
311         }
312
313         if (opt_destination) {
314                 SAFE_FREE(server_name);
315                 if ((server_name = SMB_STRDUP(opt_destination)) == NULL) {
316                         return NT_STATUS_NO_MEMORY;
317                 }
318         }
319
320         /* make a connection to a named pipe */
321         nt_status = connect_to_ipc(&cli_tmp, NULL, server_name);
322         if (!NT_STATUS_IS_OK(nt_status)) {
323                 SAFE_FREE(server_name);
324                 return nt_status;
325         }
326
327         pipe_hnd = cli_rpc_pipe_open_noauth(cli_tmp, pipe_num, &nt_status);
328         if (!pipe_hnd) {
329                 DEBUG(0, ("couldn't not initialize pipe\n"));
330                 cli_shutdown(cli_tmp);
331                 SAFE_FREE(server_name);
332                 return nt_status;
333         }
334
335         *cli_dst = cli_tmp;
336         *pp_pipe_hnd = pipe_hnd;
337         SAFE_FREE(server_name);
338
339         return nt_status;
340 }
341
342 /****************************************************************************
343  Use the local machine account (krb) and password for this session.
344 ****************************************************************************/
345
346 int net_use_krb_machine_account(void) 
347 {
348         char *user_name = NULL;
349
350         if (!secrets_init()) {
351                 d_fprintf(stderr, "ERROR: Unable to open secrets database\n");
352                 exit(1);
353         }
354
355         opt_password = secrets_fetch_machine_password(opt_target_workgroup, NULL, NULL);
356         if (asprintf(&user_name, "%s$@%s", global_myname(), lp_realm()) == -1) {
357                 return -1;
358         }
359         opt_user_name = user_name;
360         return 0;
361 }
362
363 /****************************************************************************
364  Use the machine account name and password for this session.
365 ****************************************************************************/
366
367 int net_use_machine_account(void)
368 {
369         char *user_name = NULL;
370                 
371         if (!secrets_init()) {
372                 d_fprintf(stderr, "ERROR: Unable to open secrets database\n");
373                 exit(1);
374         }
375
376         opt_password = secrets_fetch_machine_password(opt_target_workgroup, NULL, NULL);
377         if (asprintf(&user_name, "%s$", global_myname()) == -1) {
378                 return -1;
379         }
380         opt_user_name = user_name;
381         return 0;
382 }
383
384 BOOL net_find_server(const char *domain, unsigned flags, struct in_addr *server_ip, char **server_name)
385 {
386         const char *d = domain ? domain : opt_target_workgroup;
387
388         if (opt_host) {
389                 *server_name = SMB_STRDUP(opt_host);
390         }               
391
392         if (opt_have_ip) {
393                 *server_ip = opt_dest_ip;
394                 if (!*server_name) {
395                         *server_name = SMB_STRDUP(inet_ntoa(opt_dest_ip));
396                 }
397         } else if (*server_name) {
398                 /* resolve the IP address */
399                 if (!resolve_name(*server_name, server_ip, 0x20))  {
400                         DEBUG(1,("Unable to resolve server name\n"));
401                         return False;
402                 }
403         } else if (flags & NET_FLAGS_PDC) {
404                 struct in_addr pdc_ip;
405
406                 if (get_pdc_ip(d, &pdc_ip)) {
407                         fstring dc_name;
408                         
409                         if (is_zero_ip_v4(pdc_ip))
410                                 return False;
411                         
412                         if ( !name_status_find(d, 0x1b, 0x20, pdc_ip, dc_name) )
413                                 return False;
414                                 
415                         *server_name = SMB_STRDUP(dc_name);
416                         *server_ip = pdc_ip;
417                 }
418         } else if (flags & NET_FLAGS_DMB) {
419                 struct in_addr msbrow_ip;
420                 /*  if (!resolve_name(MSBROWSE, &msbrow_ip, 1)) */
421                 if (!resolve_name(d, &msbrow_ip, 0x1B))  {
422                         DEBUG(1,("Unable to resolve domain browser via name lookup\n"));
423                         return False;
424                 } else {
425                         *server_ip = msbrow_ip;
426                 }
427                 *server_name = SMB_STRDUP(inet_ntoa(opt_dest_ip));
428         } else if (flags & NET_FLAGS_MASTER) {
429                 struct in_addr brow_ips;
430                 if (!resolve_name(d, &brow_ips, 0x1D))  {
431                                 /* go looking for workgroups */
432                         DEBUG(1,("Unable to resolve master browser via name lookup\n"));
433                         return False;
434                 } else {
435                         *server_ip = brow_ips;
436                 }
437                 *server_name = SMB_STRDUP(inet_ntoa(opt_dest_ip));
438         } else if (!(flags & NET_FLAGS_LOCALHOST_DEFAULT_INSANE)) {
439                 (*server_ip).s_addr = htonl(INADDR_LOOPBACK);
440                 *server_name = SMB_STRDUP("127.0.0.1");
441         }
442
443         if (!server_name || !*server_name) {
444                 DEBUG(1,("no server to connect to\n"));
445                 return False;
446         }
447
448         return True;
449 }
450
451
452 BOOL net_find_pdc(struct in_addr *server_ip, fstring server_name, const char *domain_name)
453 {
454         if (get_pdc_ip(domain_name, server_ip)) {
455                 if (is_zero_ip_v4(*server_ip))
456                         return False;
457                 
458                 if (!name_status_find(domain_name, 0x1b, 0x20, *server_ip, server_name))
459                         return False;
460                         
461                 return True;    
462         } 
463         else
464                 return False;
465 }
466
467 NTSTATUS net_make_ipc_connection(unsigned flags, struct cli_state **pcli)
468 {
469         return net_make_ipc_connection_ex(NULL, NULL, NULL, flags, pcli);
470 }
471
472 NTSTATUS net_make_ipc_connection_ex(const char *domain, const char *server,
473                                     struct in_addr *ip, unsigned flags,
474                                     struct cli_state **pcli)
475 {
476         char *server_name = NULL;
477         struct in_addr server_ip;
478         struct cli_state *cli = NULL;
479         NTSTATUS nt_status;
480
481         if ( !server || !ip ) {
482                 if (!net_find_server(domain, flags, &server_ip, &server_name)) {
483                         d_fprintf(stderr, "Unable to find a suitable server\n");
484                         nt_status = NT_STATUS_UNSUCCESSFUL;
485                         goto done;
486                 }
487         } else {
488                 server_name = SMB_STRDUP( server );
489                 server_ip = *ip;
490         }
491
492         if (flags & NET_FLAGS_ANONYMOUS) {
493                 nt_status = connect_to_ipc_anonymous(&cli, &server_ip, server_name);
494         } else {
495                 nt_status = connect_to_ipc(&cli, &server_ip, server_name);
496         }
497
498         /* store the server in the affinity cache if it was a PDC */
499
500         if ( (flags & NET_FLAGS_PDC) && NT_STATUS_IS_OK(nt_status) )
501                 saf_store( cli->server_domain, cli->desthost );
502
503         SAFE_FREE(server_name);
504         if (!NT_STATUS_IS_OK(nt_status)) {
505                 d_fprintf(stderr, "Connection failed: %s\n",
506                           nt_errstr(nt_status));
507                 cli = NULL;
508         }
509
510 done:
511         if (pcli != NULL) {
512                 *pcli = cli;
513         }
514         return nt_status;
515 }
516
517 static int net_user(int argc, const char **argv)
518 {
519         if (net_ads_check() == 0)
520                 return net_ads_user(argc, argv);
521
522         /* if server is not specified, default to PDC? */
523         if (net_rpc_check(NET_FLAGS_PDC))
524                 return net_rpc_user(argc, argv);
525
526         return net_rap_user(argc, argv);
527 }
528
529 static int net_group(int argc, const char **argv)
530 {
531         if (net_ads_check() == 0)
532                 return net_ads_group(argc, argv);
533
534         if (argc == 0 && net_rpc_check(NET_FLAGS_PDC))
535                 return net_rpc_group(argc, argv);
536
537         return net_rap_group(argc, argv);
538 }
539
540 static int net_join(int argc, const char **argv)
541 {
542         if (net_ads_check_our_domain() == 0) {
543                 if (net_ads_join(argc, argv) == 0)
544                         return 0;
545                 else
546                         d_fprintf(stderr, "ADS join did not work, falling back to RPC...\n");
547         }
548         return net_rpc_join(argc, argv);
549 }
550
551 static int net_changetrustpw(int argc, const char **argv)
552 {
553         if (net_ads_check_our_domain() == 0)
554                 return net_ads_changetrustpw(argc, argv);
555
556         return net_rpc_changetrustpw(argc, argv);
557 }
558
559 static void set_line_buffering(FILE *f)
560 {
561         setvbuf(f, NULL, _IOLBF, 0);
562 }
563
564 static int net_changesecretpw(int argc, const char **argv)
565 {
566         char *trust_pw;
567         uint32 sec_channel_type = SEC_CHAN_WKSTA;
568
569         if(opt_force) {
570                 if (opt_stdin) {
571                         set_line_buffering(stdin);
572                         set_line_buffering(stdout);
573                         set_line_buffering(stderr);
574                 }
575
576                 trust_pw = get_pass("Enter machine password: ", opt_stdin);
577
578                 if (!secrets_store_machine_password(trust_pw, lp_workgroup(), sec_channel_type)) {
579                             d_fprintf(stderr, "Unable to write the machine account password in the secrets database");
580                             return 1;
581                 }
582                 else {
583                     d_printf("Modified trust account password in secrets database\n");
584                 }
585         }
586         else {
587                 d_printf("Machine account password change requires the -f flag.\n");
588                 d_printf("Do NOT use this function unless you know what it does!\n");
589                 d_printf("This function will change the ADS Domain member machine account password in the secrets.tdb file!\n");
590         }
591
592         return 0;
593 }
594
595 static int net_share(int argc, const char **argv)
596 {
597         if (net_rpc_check(0))
598                 return net_rpc_share(argc, argv);
599         return net_rap_share(argc, argv);
600 }
601
602 static int net_file(int argc, const char **argv)
603 {
604         if (net_rpc_check(0))
605                 return net_rpc_file(argc, argv);
606         return net_rap_file(argc, argv);
607 }
608
609 /*
610  Retrieve our local SID or the SID for the specified name
611  */
612 static int net_getlocalsid(int argc, const char **argv)
613 {
614         DOM_SID sid;
615         const char *name;
616         fstring sid_str;
617
618         if (argc >= 1) {
619                 name = argv[0];
620         }
621         else {
622                 name = global_myname();
623         }
624
625         if(!initialize_password_db(False, NULL)) {
626                 DEBUG(0, ("WARNING: Could not open passdb - local sid may not reflect passdb\n"
627                           "backend knowledge (such as the sid stored in LDAP)\n"));
628         }
629
630         /* first check to see if we can even access secrets, so we don't
631            panic when we can't. */
632
633         if (!secrets_init()) {
634                 d_fprintf(stderr, "Unable to open secrets.tdb.  Can't fetch domain SID for name: %s\n", name);
635                 return 1;
636         }
637
638         /* Generate one, if it doesn't exist */
639         get_global_sam_sid();
640
641         if (!secrets_fetch_domain_sid(name, &sid)) {
642                 DEBUG(0, ("Can't fetch domain SID for name: %s\n", name));
643                 return 1;
644         }
645         sid_to_string(sid_str, &sid);
646         d_printf("SID for domain %s is: %s\n", name, sid_str);
647         return 0;
648 }
649
650 static int net_setlocalsid(int argc, const char **argv)
651 {
652         DOM_SID sid;
653
654         if ( (argc != 1)
655              || (strncmp(argv[0], "S-1-5-21-", strlen("S-1-5-21-")) != 0)
656              || (!string_to_sid(&sid, argv[0]))
657              || (sid.num_auths != 4)) {
658                 d_printf("usage: net setlocalsid S-1-5-21-x-y-z\n");
659                 return 1;
660         }
661
662         if (!secrets_store_domain_sid(global_myname(), &sid)) {
663                 DEBUG(0,("Can't store domain SID as a pdc/bdc.\n"));
664                 return 1;
665         }
666
667         return 0;
668 }
669
670 static int net_setdomainsid(int argc, const char **argv)
671 {
672         DOM_SID sid;
673
674         if ( (argc != 1)
675              || (strncmp(argv[0], "S-1-5-21-", strlen("S-1-5-21-")) != 0)
676              || (!string_to_sid(&sid, argv[0]))
677              || (sid.num_auths != 4)) {
678                 d_printf("usage: net setdomainsid S-1-5-21-x-y-z\n");
679                 return 1;
680         }
681
682         if (!secrets_store_domain_sid(lp_workgroup(), &sid)) {
683                 DEBUG(0,("Can't store domain SID.\n"));
684                 return 1;
685         }
686
687         return 0;
688 }
689
690 static int net_getdomainsid(int argc, const char **argv)
691 {
692         DOM_SID domain_sid;
693         fstring sid_str;
694
695         if(!initialize_password_db(False, NULL)) {
696                 DEBUG(0, ("WARNING: Could not open passdb - domain sid may not reflect passdb\n"
697                           "backend knowledge (such as the sid stored in LDAP)\n"));
698         }
699
700         /* first check to see if we can even access secrets, so we don't
701            panic when we can't. */
702
703         if (!secrets_init()) {
704                 d_fprintf(stderr, "Unable to open secrets.tdb.  Can't fetch domain"
705                                   "SID for name: %s\n", get_global_sam_name());
706                 return 1;
707         }
708
709         /* Generate one, if it doesn't exist */
710         get_global_sam_sid();
711
712         if (!secrets_fetch_domain_sid(global_myname(), &domain_sid)) {
713                 d_fprintf(stderr, "Could not fetch local SID\n");
714                 return 1;
715         }
716         sid_to_string(sid_str, &domain_sid);
717         d_printf("SID for domain %s is: %s\n", global_myname(), sid_str);
718
719         if (!secrets_fetch_domain_sid(opt_workgroup, &domain_sid)) {
720                 d_fprintf(stderr, "Could not fetch domain SID\n");
721                 return 1;
722         }
723
724         sid_to_string(sid_str, &domain_sid);
725         d_printf("SID for domain %s is: %s\n", opt_workgroup, sid_str);
726
727         return 0;
728 }
729
730 #ifdef WITH_FAKE_KASERVER
731
732 int net_help_afs(int argc, const char **argv)
733 {
734         d_printf("  net afs key filename\n"
735                  "\tImports a OpenAFS KeyFile into our secrets.tdb\n\n");
736         d_printf("  net afs impersonate <user> <cell>\n"
737                  "\tCreates a token for user@cell\n\n");
738         return -1;
739 }
740
741 static int net_afs_key(int argc, const char **argv)
742 {
743         int fd;
744         struct afs_keyfile keyfile;
745
746         if (argc != 2) {
747                 d_printf("usage: 'net afs key <keyfile> cell'\n");
748                 return -1;
749         }
750
751         if (!secrets_init()) {
752                 d_fprintf(stderr, "Could not open secrets.tdb\n");
753                 return -1;
754         }
755
756         if ((fd = open(argv[0], O_RDONLY, 0)) < 0) {
757                 d_fprintf(stderr, "Could not open %s\n", argv[0]);
758                 return -1;
759         }
760
761         if (read(fd, &keyfile, sizeof(keyfile)) != sizeof(keyfile)) {
762                 d_fprintf(stderr, "Could not read keyfile\n");
763                 return -1;
764         }
765
766         if (!secrets_store_afs_keyfile(argv[1], &keyfile)) {
767                 d_fprintf(stderr, "Could not write keyfile to secrets.tdb\n");
768                 return -1;
769         }
770
771         return 0;
772 }
773
774 static int net_afs_impersonate(int argc, const char **argv)
775 {
776         char *token;
777
778         if (argc != 2) {
779                 fprintf(stderr, "Usage: net afs impersonate <user> <cell>\n");
780                 exit(1);
781         }
782
783         token = afs_createtoken_str(argv[0], argv[1]);
784
785         if (token == NULL) {
786                 fprintf(stderr, "Could not create token\n");
787                 exit(1);
788         }
789
790         if (!afs_settoken_str(token)) {
791                 fprintf(stderr, "Could not set token into kernel\n");
792                 exit(1);
793         }
794
795         printf("Success: %s@%s\n", argv[0], argv[1]);
796         return 0;
797 }
798
799 static int net_afs(int argc, const char **argv)
800 {
801         struct functable func[] = {
802                 {"key", net_afs_key},
803                 {"impersonate", net_afs_impersonate},
804                 {"help", net_help_afs},
805                 {NULL, NULL}
806         };
807         return net_run_function(argc, argv, func, net_help_afs);
808 }
809
810 #endif /* WITH_FAKE_KASERVER */
811
812 static BOOL search_maxrid(struct pdb_search *search, const char *type,
813                           uint32 *max_rid)
814 {
815         struct samr_displayentry *entries;
816         uint32 i, num_entries;
817
818         if (search == NULL) {
819                 d_fprintf(stderr, "get_maxrid: Could not search %s\n", type);
820                 return False;
821         }
822
823         num_entries = pdb_search_entries(search, 0, 0xffffffff, &entries);
824         for (i=0; i<num_entries; i++)
825                 *max_rid = MAX(*max_rid, entries[i].rid);
826         pdb_search_destroy(search);
827         return True;
828 }
829
830 static uint32 get_maxrid(void)
831 {
832         uint32 max_rid = 0;
833
834         if (!search_maxrid(pdb_search_users(0), "users", &max_rid))
835                 return 0;
836
837         if (!search_maxrid(pdb_search_groups(), "groups", &max_rid))
838                 return 0;
839
840         if (!search_maxrid(pdb_search_aliases(get_global_sam_sid()),
841                            "aliases", &max_rid))
842                 return 0;
843         
844         return max_rid;
845 }
846
847 static int net_maxrid(int argc, const char **argv)
848 {
849         uint32 rid;
850
851         if (argc != 0) {
852                 DEBUG(0, ("usage: net maxrid\n"));
853                 return 1;
854         }
855
856         if ((rid = get_maxrid()) == 0) {
857                 DEBUG(0, ("can't get current maximum rid\n"));
858                 return 1;
859         }
860
861         d_printf("Currently used maximum rid: %d\n", rid);
862
863         return 0;
864 }
865
866 /****************************************************************************
867 ****************************************************************************/
868
869 const char *net_prompt_pass(const char *user)
870 {
871         char *prompt = NULL;
872         const char *pass = NULL;
873
874         if (opt_password) {
875                 return opt_password;
876         }
877
878         if (opt_machine_pass) {
879                 return NULL;
880         }
881
882         asprintf(&prompt, "Enter %s's password:", user);
883         if (!prompt) {
884                 return NULL;
885         }
886
887         pass = getpass(prompt);
888         SAFE_FREE(prompt);
889
890         return pass;
891 }
892
893 /* main function table */
894 static struct functable net_func[] = {
895         {"RPC", net_rpc},
896         {"RAP", net_rap},
897         {"ADS", net_ads},
898
899         /* eventually these should auto-choose the transport ... */
900         {"FILE", net_file},
901         {"SHARE", net_share},
902         {"SESSION", net_rap_session},
903         {"SERVER", net_rap_server},
904         {"DOMAIN", net_rap_domain},
905         {"PRINTQ", net_rap_printq},
906         {"USER", net_user},
907         {"GROUP", net_group},
908         {"GROUPMAP", net_groupmap},
909         {"SAM", net_sam},
910         {"VALIDATE", net_rap_validate},
911         {"GROUPMEMBER", net_rap_groupmember},
912         {"ADMIN", net_rap_admin},
913         {"SERVICE", net_rap_service},   
914         {"PASSWORD", net_rap_password},
915         {"CHANGETRUSTPW", net_changetrustpw},
916         {"CHANGESECRETPW", net_changesecretpw},
917         {"TIME", net_time},
918         {"LOOKUP", net_lookup},
919         {"JOIN", net_join},
920         {"CACHE", net_cache},
921         {"GETLOCALSID", net_getlocalsid},
922         {"SETLOCALSID", net_setlocalsid},
923         {"SETDOMAINSID", net_setdomainsid},
924         {"GETDOMAINSID", net_getdomainsid},
925         {"MAXRID", net_maxrid},
926         {"IDMAP", net_idmap},
927         {"STATUS", net_status},
928         {"USERSHARE", net_usershare},
929         {"USERSIDLIST", net_usersidlist},
930         {"CONF", net_conf},
931 #ifdef WITH_FAKE_KASERVER
932         {"AFS", net_afs},
933 #endif
934
935         {"HELP", net_help},
936         {NULL, NULL}
937 };
938
939
940 /****************************************************************************
941   main program
942 ****************************************************************************/
943  int main(int argc, const char **argv)
944 {
945         int opt,i;
946         char *p;
947         int rc = 0;
948         int argc_new = 0;
949         const char ** argv_new;
950         poptContext pc;
951
952         struct poptOption long_options[] = {
953                 {"help",        'h', POPT_ARG_NONE,   0, 'h'},
954                 {"workgroup",   'w', POPT_ARG_STRING, &opt_target_workgroup},
955                 {"user",        'U', POPT_ARG_STRING, &opt_user_name, 'U'},
956                 {"ipaddress",   'I', POPT_ARG_STRING, 0,'I'},
957                 {"port",        'p', POPT_ARG_INT,    &opt_port},
958                 {"myname",      'n', POPT_ARG_STRING, &opt_requester_name},
959                 {"server",      'S', POPT_ARG_STRING, &opt_host},
960                 {"container",   'c', POPT_ARG_STRING, &opt_container},
961                 {"comment",     'C', POPT_ARG_STRING, &opt_comment},
962                 {"maxusers",    'M', POPT_ARG_INT,    &opt_maxusers},
963                 {"flags",       'F', POPT_ARG_INT,    &opt_flags},
964                 {"long",        'l', POPT_ARG_NONE,   &opt_long_list_entries},
965                 {"reboot",      'r', POPT_ARG_NONE,   &opt_reboot},
966                 {"force",       'f', POPT_ARG_NONE,   &opt_force},
967                 {"stdin",       'i', POPT_ARG_NONE,   &opt_stdin},
968                 {"timeout",     't', POPT_ARG_INT,    &opt_timeout},
969                 {"machine-pass",'P', POPT_ARG_NONE,   &opt_machine_pass},
970                 {"myworkgroup", 'W', POPT_ARG_STRING, &opt_workgroup},
971                 {"verbose",     'v', POPT_ARG_NONE,   &opt_verbose},
972                 {"test",        'T', POPT_ARG_NONE,   &opt_testmode},
973                 /* Options for 'net groupmap set' */
974                 {"local",       'L', POPT_ARG_NONE,   &opt_localgroup},
975                 {"domain",      'D', POPT_ARG_NONE,   &opt_domaingroup},
976                 {"ntname",      'N', POPT_ARG_STRING, &opt_newntname},
977                 {"rid",         'R', POPT_ARG_INT,    &opt_rid},
978                 /* Options for 'net rpc share migrate' */
979                 {"acls",        0, POPT_ARG_NONE,     &opt_acls},
980                 {"attrs",       0, POPT_ARG_NONE,     &opt_attrs},
981                 {"timestamps",  0, POPT_ARG_NONE,     &opt_timestamps},
982                 {"exclude",     'e', POPT_ARG_STRING, &opt_exclude},
983                 {"destination", 0, POPT_ARG_STRING,   &opt_destination},
984                 {"tallocreport", 0, POPT_ARG_NONE, &do_talloc_report},
985
986                 POPT_COMMON_SAMBA
987                 { 0, 0, 0, 0}
988         };
989
990         TALLOC_CTX *frame = talloc_stackframe();
991
992         zero_ip_v4(&opt_dest_ip);
993
994         load_case_tables();
995
996         /* set default debug level to 0 regardless of what smb.conf sets */
997         DEBUGLEVEL_CLASS[DBGC_ALL] = 0;
998         dbf = x_stderr;
999         
1000         pc = poptGetContext(NULL, argc, (const char **) argv, long_options, 
1001                             POPT_CONTEXT_KEEP_FIRST);
1002         
1003         while((opt = poptGetNextOpt(pc)) != -1) {
1004                 switch (opt) {
1005                 case 'h':
1006                         net_help(argc, argv);
1007                         exit(0);
1008                         break;
1009                 case 'I':
1010                         opt_dest_ip = *interpret_addr2(poptGetOptArg(pc));
1011                         if (is_zero_ip_v4(opt_dest_ip))
1012                                 d_fprintf(stderr, "\nInvalid ip address specified\n");
1013                         else
1014                                 opt_have_ip = True;
1015                         break;
1016                 case 'U':
1017                         opt_user_specified = True;
1018                         opt_user_name = SMB_STRDUP(opt_user_name);
1019                         p = strchr(opt_user_name,'%');
1020                         if (p) {
1021                                 *p = 0;
1022                                 opt_password = p+1;
1023                         }
1024                         break;
1025                 default:
1026                         d_fprintf(stderr, "\nInvalid option %s: %s\n", 
1027                                  poptBadOption(pc, 0), poptStrerror(opt));
1028                         net_help(argc, argv);
1029                         exit(1);
1030                 }
1031         }
1032         
1033         /*
1034          * Don't load debug level from smb.conf. It should be
1035          * set by cmdline arg or remain default (0)
1036          */
1037         AllowDebugChange = False;
1038         lp_load(dyn_CONFIGFILE,True,False,False,True);
1039         
1040         argv_new = (const char **)poptGetArgs(pc);
1041
1042         argc_new = argc;
1043         for (i=0; i<argc; i++) {
1044                 if (argv_new[i] == NULL) {
1045                         argc_new = i;
1046                         break;
1047                 }
1048         }
1049
1050         if (do_talloc_report) {
1051                 talloc_enable_leak_report();
1052         }
1053
1054         if (opt_requester_name) {
1055                 set_global_myname(opt_requester_name);
1056         }
1057
1058         if (!opt_user_name && getenv("LOGNAME")) {
1059                 opt_user_name = getenv("LOGNAME");
1060         }
1061
1062         if (!opt_workgroup) {
1063                 opt_workgroup = smb_xstrdup(lp_workgroup());
1064         }
1065         
1066         if (!opt_target_workgroup) {
1067                 opt_target_workgroup = smb_xstrdup(lp_workgroup());
1068         }
1069         
1070         if (!init_names())
1071                 exit(1);
1072
1073         load_interfaces();
1074         
1075         /* this makes sure that when we do things like call scripts, 
1076            that it won't assert becouse we are not root */
1077         sec_init();
1078
1079         if (opt_machine_pass) {
1080                 /* it is very useful to be able to make ads queries as the
1081                    machine account for testing purposes and for domain leave */
1082
1083                 net_use_krb_machine_account();
1084         }
1085
1086         if (!opt_password) {
1087                 opt_password = getenv("PASSWD");
1088         }
1089          
1090         rc = net_run_function(argc_new-1, argv_new+1, net_func, net_help);
1091         
1092         DEBUG(2,("return code = %d\n", rc));
1093         TALLOC_FREE(frame);
1094         return rc;
1095 }