Fix segfault by getting this the right way around
[tprouty/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 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_port = 0;
69 int opt_maxusers = -1;
70 const char *opt_comment = "";
71 const char *opt_container = "cn=Users";
72 int opt_flags = -1;
73 int opt_timeout = 0;
74 const char *opt_target_workgroup = NULL;
75 static int opt_machine_pass = 0;
76
77 BOOL opt_have_ip = False;
78 struct in_addr opt_dest_ip;
79
80 uint32 get_sec_channel_type(const char *param) 
81 {
82         if (!(param && *param)) {
83                 return get_default_sec_channel();
84         } else {
85                 if (strcasecmp(param, "PDC")==0) {
86                         return SEC_CHAN_BDC;
87                 } else if (strcasecmp(param, "BDC")==0) {
88                         return SEC_CHAN_BDC;
89                 } else if (strcasecmp(param, "MEMBER")==0) {
90                         return SEC_CHAN_WKSTA;
91 #if 0                   
92                 } else if (strcasecmp(param, "DOMAIN")==0) {
93                         return SEC_CHAN_DOMAIN;
94 #endif
95                 } else {
96                         return get_default_sec_channel();
97                 }
98         }
99 }
100
101 /*
102   run a function from a function table. If not found then
103   call the specified usage function 
104 */
105 int net_run_function(int argc, const char **argv, struct functable *table, 
106                      int (*usage_fn)(int argc, const char **argv))
107 {
108         int i;
109         
110         if (argc < 1) {
111                 d_printf("\nUsage: \n");
112                 return usage_fn(argc, argv);
113         }
114         for (i=0; table[i].funcname; i++) {
115                 if (StrCaseCmp(argv[0], table[i].funcname) == 0)
116                         return table[i].fn(argc-1, argv+1);
117         }
118         d_printf("No command: %s\n", argv[0]);
119         return usage_fn(argc, argv);
120 }
121
122
123 /****************************************************************************
124 connect to \\server\ipc$  
125 ****************************************************************************/
126 NTSTATUS connect_to_ipc(struct cli_state **c, struct in_addr *server_ip,
127                                         const char *server_name)
128 {
129         NTSTATUS nt_status;
130
131         if (!opt_password) {
132                 char *pass = getpass("Password:");
133                 if (pass) {
134                         opt_password = strdup(pass);
135                 }
136         }
137         
138         nt_status = cli_full_connection(c, opt_requester_name, server_name, 
139                                         server_ip, opt_port,
140                                         "IPC$", "IPC",  
141                                         opt_user_name, opt_workgroup,
142                                         opt_password, 0, NULL);
143         
144         if (NT_STATUS_IS_OK(nt_status)) {
145                 return nt_status;
146         } else {
147                 DEBUG(1,("Cannot connect to server.  Error was %s\n", 
148                          nt_errstr(nt_status)));
149
150                 /* Display a nicer message depending on the result */
151
152                 if (NT_STATUS_V(nt_status) == 
153                     NT_STATUS_V(NT_STATUS_LOGON_FAILURE))
154                         d_printf("The username or password was not correct.\n");
155
156                 return nt_status;
157         }
158 }
159
160 /****************************************************************************
161 connect to \\server\ipc$ anonymously
162 ****************************************************************************/
163 NTSTATUS connect_to_ipc_anonymous(struct cli_state **c,
164                         struct in_addr *server_ip, const char *server_name)
165 {
166         NTSTATUS nt_status;
167
168         nt_status = cli_full_connection(c, opt_requester_name, server_name, 
169                                         server_ip, opt_port,
170                                         "IPC$", "IPC",  
171                                         "", "",
172                                         "", 0, NULL);
173         
174         if (NT_STATUS_IS_OK(nt_status)) {
175                 return nt_status;
176         } else {
177                 DEBUG(1,("Cannot connect to server (anonymously).  Error was %s\n", nt_errstr(nt_status)));
178                 return nt_status;
179         }
180 }
181
182 BOOL net_find_server(unsigned flags, struct in_addr *server_ip, char **server_name)
183 {
184
185         if (opt_host) {
186                 *server_name = strdup(opt_host);
187         }               
188
189         if (opt_have_ip) {
190                 *server_ip = opt_dest_ip;
191                 if (!*server_name) {
192                         *server_name = strdup(inet_ntoa(opt_dest_ip));
193                 }
194         } else if (*server_name) {
195                 /* resolve the IP address */
196                 if (!resolve_name(*server_name, server_ip, 0x20))  {
197                         DEBUG(1,("Unable to resolve server name\n"));
198                         return False;
199                 }
200         } else if (flags & NET_FLAGS_PDC) {
201                 struct in_addr pdc_ip;
202
203                 if (get_pdc_ip(opt_target_workgroup, &pdc_ip)) {
204                         fstring dc_name;
205                         
206                         if (is_zero_ip(pdc_ip))
207                                 return False;
208                         
209                         if (!lookup_dc_name(global_myname(), opt_target_workgroup, &pdc_ip, dc_name))
210                                 return False;
211                                 
212                         *server_name = strdup(dc_name);
213                         *server_ip = pdc_ip;
214                 }
215                 
216         } else if (flags & NET_FLAGS_DMB) {
217                 struct in_addr msbrow_ip;
218                 /*  if (!resolve_name(MSBROWSE, &msbrow_ip, 1)) */
219                 if (!resolve_name(opt_target_workgroup, &msbrow_ip, 0x1B))  {
220                         DEBUG(1,("Unable to resolve domain browser via name lookup\n"));
221                         return False;
222                 } else {
223                         *server_ip = msbrow_ip;
224                 }
225                 *server_name = strdup(inet_ntoa(opt_dest_ip));
226         } else if (flags & NET_FLAGS_MASTER) {
227                 struct in_addr brow_ips;
228                 if (!resolve_name(opt_target_workgroup, &brow_ips, 0x1D))  {
229                                 /* go looking for workgroups */
230                         DEBUG(1,("Unable to resolve master browser via name lookup\n"));
231                         return False;
232                 } else {
233                         *server_ip = brow_ips;
234                 }
235                 *server_name = strdup(inet_ntoa(opt_dest_ip));
236         } else if (!(flags & NET_FLAGS_LOCALHOST_DEFAULT_INSANE)) {
237                 extern struct in_addr loopback_ip;
238                 *server_ip = loopback_ip;
239                 *server_name = strdup("127.0.0.1");
240         }
241
242         if (!server_name || !*server_name) {
243                 DEBUG(1,("no server to connect to\n"));
244                 return False;
245         }
246
247         return True;
248 }
249
250
251 BOOL net_find_dc(struct in_addr *server_ip, fstring server_name, const char *domain_name)
252 {
253         if (get_pdc_ip(domain_name, server_ip)) {
254                 fstring dc_name;
255                         
256                 if (is_zero_ip(*server_ip))
257                         return False;
258                 
259                 if (!lookup_dc_name(global_myname(), domain_name, server_ip, dc_name))
260                         return False;
261                         
262                 fstrcpy(server_name, dc_name);
263                 return True;
264         } else
265                 return False;
266 }
267
268
269 struct cli_state *net_make_ipc_connection(unsigned flags)
270 {
271         char *server_name = NULL;
272         struct in_addr server_ip;
273         struct cli_state *cli = NULL;
274         NTSTATUS nt_status;
275
276         if (!net_find_server(flags, &server_ip, &server_name)) {
277                 d_printf("\nUnable to find a suitable server\n");
278                 return NULL;
279         }
280
281         if (flags & NET_FLAGS_ANONYMOUS) {
282                 nt_status = connect_to_ipc_anonymous(&cli, &server_ip, server_name);
283         } else {
284                 nt_status = connect_to_ipc(&cli, &server_ip, server_name);
285         }
286
287         SAFE_FREE(server_name);
288         if (NT_STATUS_IS_OK(nt_status)) {
289                 return cli;
290         } else {
291                 return NULL;
292         }
293 }
294
295 static int net_user(int argc, const char **argv)
296 {
297         if (net_ads_check() == 0)
298                 return net_ads_user(argc, argv);
299
300         /* if server is not specified, default to PDC? */
301         if (net_rpc_check(NET_FLAGS_PDC))
302                 return net_rpc_user(argc, argv);
303
304         return net_rap_user(argc, argv);
305 }
306
307 static int net_group(int argc, const char **argv)
308 {
309         if (net_ads_check() == 0)
310                 return net_ads_group(argc, argv);
311
312         if (argc == 0 && net_rpc_check(NET_FLAGS_PDC))
313                 return net_rpc_group(argc, argv);
314
315         return net_rap_group(argc, argv);
316 }
317
318 static int net_join(int argc, const char **argv)
319 {
320         if (net_ads_check() == 0) {
321                 if (net_ads_join(argc, argv) == 0)
322                         return 0;
323                 else
324                         d_printf("ADS join did not work, trying RPC...\n");
325         }
326         return net_rpc_join(argc, argv);
327 }
328
329 static int net_changetrustpw(int argc, const char **argv)
330 {
331         if (net_ads_check() == 0)
332                 return net_ads_changetrustpw(argc, argv);
333
334         return net_rpc_changetrustpw(argc, argv);
335 }
336
337 static int net_share(int argc, const char **argv)
338 {
339         if (net_rpc_check(0))
340                 return net_rpc_share(argc, argv);
341         return net_rap_share(argc, argv);
342 }
343
344 static int net_file(int argc, const char **argv)
345 {
346         if (net_rpc_check(0))
347                 return net_rpc_file(argc, argv);
348         return net_rap_file(argc, argv);
349 }
350
351 /*
352  Retrieve our local SID or the SID for the specified name
353  */
354 static int net_getlocalsid(int argc, const char **argv)
355 {
356         DOM_SID sid;
357         const char *name;
358         fstring sid_str;
359
360         if (argc >= 1) {
361                 name = argv[0];
362         }
363         else {
364                 name = global_myname();
365         }
366
367         if (!secrets_fetch_domain_sid(name, &sid)) {
368                 DEBUG(0, ("Can't fetch domain SID for name: %s\n", name));      
369                 return 1;
370         }
371         sid_to_string(sid_str, &sid);
372         d_printf("SID for domain %s is: %s\n", name, sid_str);
373         return 0;
374 }
375
376 static int net_setlocalsid(int argc, const char **argv)
377 {
378         DOM_SID sid;
379
380         if ( (argc != 1)
381              || (strncmp(argv[0], "S-1-5-21-", strlen("S-1-5-21-")) != 0)
382              || (!string_to_sid(&sid, argv[0]))
383              || (sid.num_auths != 4)) {
384                 d_printf("usage: net setlocalsid S-1-5-21-x-y-z\n");
385                 return 1;
386         }
387
388         if (!secrets_store_domain_sid(global_myname(), &sid)) {
389                 DEBUG(0,("Can't store domain SID as a pdc/bdc.\n"));
390                 return 1;
391         }
392
393         return 0;
394 }
395
396 static int net_getdomainsid(int argc, const char **argv)
397 {
398         DOM_SID domain_sid;
399         fstring sid_str;
400
401         if (!secrets_fetch_domain_sid(global_myname(), &domain_sid)) {
402                 d_printf("Could not fetch local SID\n");
403                 return 1;
404         }
405         sid_to_string(sid_str, &domain_sid);
406         d_printf("SID for domain %s is: %s\n", global_myname(), sid_str);
407
408         if (!secrets_fetch_domain_sid(lp_workgroup(), &domain_sid)) {
409                 d_printf("Could not fetch domain SID\n");
410                 return 1;
411         }
412
413         sid_to_string(sid_str, &domain_sid);
414         d_printf("SID for domain %s is: %s\n", lp_workgroup(), sid_str);
415
416         return 0;
417 }
418
419 static uint32 get_maxrid(void)
420 {
421         SAM_ACCOUNT *pwd = NULL;
422         uint32 max_rid = 0;
423         GROUP_MAP *map = NULL;
424         int num_entries = 0;
425         int i;
426
427         if (!pdb_setsampwent(False)) {
428                 DEBUG(0, ("load_sampwd_entries: Unable to open passdb.\n"));
429                 return 0;
430         }
431
432         for (; (NT_STATUS_IS_OK(pdb_init_sam(&pwd))) 
433                      && pdb_getsampwent(pwd) == True; pwd=NULL) {
434                 uint32 rid;
435
436                 if (!sid_peek_rid(pdb_get_user_sid(pwd), &rid)) {
437                         DEBUG(0, ("can't get RID for user '%s'\n",
438                                   pdb_get_username(pwd)));
439                         pdb_free_sam(&pwd);
440                         continue;
441                 }
442
443                 if (rid > max_rid)
444                         max_rid = rid;
445
446                 DEBUG(1,("%d is user '%s'\n", rid, pdb_get_username(pwd)));
447                 pdb_free_sam(&pwd);
448         }
449
450         pdb_endsampwent();
451         pdb_free_sam(&pwd);
452
453         if (!pdb_enum_group_mapping(SID_NAME_UNKNOWN, &map, &num_entries,
454                                     ENUM_ONLY_MAPPED, MAPPING_WITHOUT_PRIV))
455                 return max_rid;
456
457         for (i = 0; i < num_entries; i++) {
458                 uint32 rid;
459
460                 if (!sid_peek_check_rid(get_global_sam_sid(), &map[i].sid,
461                                         &rid)) {
462                         DEBUG(3, ("skipping map for group '%s', SID %s\n",
463                                   map[i].nt_name,
464                                   sid_string_static(&map[i].sid)));
465                         continue;
466                 }
467                 DEBUG(1,("%d is group '%s'\n", rid, map[i].nt_name));
468
469                 if (rid > max_rid)
470                         max_rid = rid;
471         }
472
473         SAFE_FREE(map);
474
475         return max_rid;
476 }
477
478 static int net_maxrid(int argc, const char **argv)
479 {
480         uint32 rid;
481
482         if (argc != 0) {
483                 DEBUG(0, ("usage: net maxrid\n"));
484                 return 1;
485         }
486
487         if ((rid = get_maxrid()) == 0) {
488                 DEBUG(0, ("can't get current maximum rid\n"));
489                 return 1;
490         }
491
492         d_printf("Currently used maximum rid: %d\n", rid);
493
494         return 0;
495 }
496
497 /* main function table */
498 static struct functable net_func[] = {
499         {"RPC", net_rpc},
500         {"RAP", net_rap},
501         {"ADS", net_ads},
502
503         /* eventually these should auto-choose the transport ... */
504         {"FILE", net_file},
505         {"SHARE", net_share},
506         {"SESSION", net_rap_session},
507         {"SERVER", net_rap_server},
508         {"DOMAIN", net_rap_domain},
509         {"PRINTQ", net_rap_printq},
510         {"USER", net_user},
511         {"GROUP", net_group},
512         {"VALIDATE", net_rap_validate},
513         {"GROUPMEMBER", net_rap_groupmember},
514         {"ADMIN", net_rap_admin},
515         {"SERVICE", net_rap_service},   
516         {"PASSWORD", net_rap_password},
517         {"CHANGETRUSTPW", net_changetrustpw},
518         {"TIME", net_time},
519         {"LOOKUP", net_lookup},
520         {"JOIN", net_join},
521         {"CACHE", net_cache},
522         {"GETLOCALSID", net_getlocalsid},
523         {"SETLOCALSID", net_setlocalsid},
524         {"GETDOMAINSID", net_getdomainsid},
525         {"MAXRID", net_maxrid},
526
527         {"HELP", net_help},
528         {NULL, NULL}
529 };
530
531
532 /****************************************************************************
533   main program
534 ****************************************************************************/
535  int main(int argc, const char **argv)
536 {
537         int opt,i;
538         char *p;
539         int rc = 0;
540         int argc_new = 0;
541         const char ** argv_new;
542         poptContext pc;
543
544         struct poptOption long_options[] = {
545                 {"help",        'h', POPT_ARG_NONE,   0, 'h'},
546                 {"workgroup",   'w', POPT_ARG_STRING, &opt_target_workgroup},
547                 {"user",        'U', POPT_ARG_STRING, &opt_user_name, 'U'},
548                 {"ipaddress",   'I', POPT_ARG_STRING, 0,'I'},
549                 {"port",        'p', POPT_ARG_INT,    &opt_port},
550                 {"myname",      'n', POPT_ARG_STRING, &opt_requester_name},
551                 {"server",      'S', POPT_ARG_STRING, &opt_host},
552                 {"container",   'c', POPT_ARG_STRING, &opt_container},
553                 {"comment",     'C', POPT_ARG_STRING, &opt_comment},
554                 {"maxusers",    'M', POPT_ARG_INT,    &opt_maxusers},
555                 {"flags",       'F', POPT_ARG_INT,    &opt_flags},
556                 {"long",        'l', POPT_ARG_NONE,   &opt_long_list_entries},
557                 {"reboot",      'r', POPT_ARG_NONE,   &opt_reboot},
558                 {"force",       'f', POPT_ARG_NONE,   &opt_force},
559                 {"timeout",     't', POPT_ARG_INT,    &opt_timeout},
560                 {"machine-pass",'P', POPT_ARG_NONE,   &opt_machine_pass},
561                 {"myworkgroup", 'W', POPT_ARG_STRING, &opt_workgroup},
562                 POPT_COMMON_SAMBA
563                 { 0, 0, 0, 0}
564         };
565
566         zero_ip(&opt_dest_ip);
567
568         dbf = x_stderr;
569         
570         pc = poptGetContext(NULL, argc, (const char **) argv, long_options, 
571                             POPT_CONTEXT_KEEP_FIRST);
572         
573         while((opt = poptGetNextOpt(pc)) != -1) {
574                 switch (opt) {
575                 case 'h':
576                         net_help(argc, argv);
577                         exit(0);
578                         break;
579                 case 'I':
580                         opt_dest_ip = *interpret_addr2(poptGetOptArg(pc));
581                         if (is_zero_ip(opt_dest_ip))
582                                 d_printf("\nInvalid ip address specified\n");
583                         else
584                                 opt_have_ip = True;
585                         break;
586                 case 'U':
587                         opt_user_specified = True;
588                         opt_user_name = strdup(opt_user_name);
589                         p = strchr(opt_user_name,'%');
590                         if (p) {
591                                 *p = 0;
592                                 opt_password = p+1;
593                         }
594                         break;
595                 default:
596                         d_printf("\nInvalid option %s: %s\n", 
597                                  poptBadOption(pc, 0), poptStrerror(opt));
598                         net_help(argc, argv);
599                         exit(1);
600                 }
601         }
602         
603         lp_load(dyn_CONFIGFILE,True,False,False);       
604
605         argv_new = (const char **)poptGetArgs(pc);
606
607         argc_new = argc;
608         for (i=0; i<argc; i++) {
609                 if (argv_new[i] == NULL) {
610                         argc_new = i;
611                         break;
612                 }
613         }
614
615         if (!opt_requester_name) {
616                 static fstring myname;
617                 get_myname(myname);
618                 opt_requester_name = myname;
619         }
620
621         if (!opt_user_name && getenv("LOGNAME")) {
622                 opt_user_name = getenv("LOGNAME");
623         }
624
625         if (!opt_workgroup) {
626                 opt_workgroup = smb_xstrdup(lp_workgroup());
627         }
628         
629         if (!opt_target_workgroup) {
630                 opt_target_workgroup = smb_xstrdup(lp_workgroup());
631         }
632         
633         if (!init_names())
634                 exit(1);
635
636         load_interfaces();
637
638         if (opt_machine_pass) {
639                 char *user = NULL;
640                 /* it is very useful to be able to make ads queries as the
641                    machine account for testing purposes and for domain leave */
642
643                 if (!secrets_init()) {
644                         d_printf("ERROR: Unable to open secrets database\n");
645                         exit(1);
646                 }
647
648                 opt_password = secrets_fetch_machine_password(opt_workgroup, NULL, NULL);
649
650                 asprintf(&user,"%s$", global_myname());
651                 opt_user_name = user;
652                 if (!opt_password) {
653                         d_printf("ERROR: Unable to fetch machine password\n");
654                         exit(1);
655                 }
656         }
657
658         if (!opt_password) {
659                 opt_password = getenv("PASSWD");
660         }
661          
662         rc = net_run_function(argc_new-1, argv_new+1, net_func, net_help);
663         
664         DEBUG(2,("return code = %d\n", rc));
665         return rc;
666 }