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