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