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