first pass at updating head branch to be to be the same as the SAMBA_2_0 branch
[sfrench/samba-autobuild/.git] / source3 / rpcclient / rpcclient.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    SMB client
5    Copyright (C) Andrew Tridgell 1994-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #ifdef SYSLOG
23 #undef SYSLOG
24 #endif
25
26 #include "includes.h"
27
28 #ifndef REGISTER
29 #define REGISTER 0
30 #endif
31
32 extern pstring debugf;
33 extern pstring scope;
34 extern pstring global_myname;
35
36 extern pstring user_socket_options;
37
38
39 extern int DEBUGLEVEL;
40
41
42 extern file_info def_finfo;
43
44 #define CNV_LANG(s) dos2unix_format(s,False)
45 #define CNV_INPUT(s) unix2dos_format(s,True)
46
47 static int process_tok(fstring tok);
48 static void cmd_help(struct client_info *info);
49 static void cmd_quit(struct client_info *info);
50
51 static struct cli_state smbcli;
52 struct cli_state *smb_cli = &smbcli;
53
54 FILE *out_hnd;
55
56 /****************************************************************************
57 initialise smb client structure
58 ****************************************************************************/
59 void rpcclient_init(void)
60 {
61         memset((char *)smb_cli, '\0', sizeof(smb_cli));
62         cli_initialise(smb_cli);
63         smb_cli->capabilities |= CAP_NT_SMBS | CAP_STATUS32;
64 }
65
66 /****************************************************************************
67 make smb client connection
68 ****************************************************************************/
69 static BOOL rpcclient_connect(struct client_info *info)
70 {
71         struct nmb_name calling;
72         struct nmb_name called;
73
74         make_nmb_name(&called , dns_to_netbios_name(info->dest_host ), info->name_type, scope);
75         make_nmb_name(&calling, dns_to_netbios_name(info->myhostname), 0x0            , scope);
76
77         if (!cli_establish_connection(smb_cli, 
78                                   info->dest_host, &info->dest_ip, 
79                                   &calling, &called,
80                                   info->share, info->svc_type,
81                                   False, True))
82         {
83                 DEBUG(0,("rpcclient_connect: connection failed\n"));
84                 cli_shutdown(smb_cli);
85                 return False;
86         }
87
88         return True;
89 }
90
91 /****************************************************************************
92 stop the smb connection(s?)
93 ****************************************************************************/
94 static void rpcclient_stop(void)
95 {
96         cli_shutdown(smb_cli);
97 }
98 /****************************************************************************
99  This defines the commands supported by this client
100  ****************************************************************************/
101 struct
102 {
103   char *name;
104   void (*fn)(struct client_info*);
105   char *description;
106 } commands[] = 
107 {
108   {"regenum",    cmd_reg_enum,         "<keyname> Registry Enumeration (keys, values)"},
109   {"regdeletekey",cmd_reg_delete_key,  "<keyname> Registry Key Delete"},
110   {"regcreatekey",cmd_reg_create_key,  "<keyname> [keyclass] Registry Key Create"},
111   {"regquerykey",cmd_reg_query_key,    "<keyname> Registry Key Query"},
112   {"regdeleteval",cmd_reg_delete_val,  "<valname> Registry Value Delete"},
113   {"regcreateval",cmd_reg_create_val,  "<valname> <valtype> <value> Registry Key Create"},
114   {"reggetsec",  cmd_reg_get_key_sec,  "<keyname> Registry Key Security"},
115   {"regtestsec", cmd_reg_test_key_sec, "<keyname> Test Registry Key Security"},
116   {"ntlogin",    cmd_netlogon_login_test, "[username] [password] NT Domain login test"},
117   {"wksinfo",    cmd_wks_query_info,   "Workstation Query Info"},
118   {"srvinfo",    cmd_srv_query_info,   "Server Query Info"},
119   {"srvsessions",cmd_srv_enum_sess,    "List sessions on a server"},
120   {"srvshares",  cmd_srv_enum_shares,  "List shares on a server"},
121   {"srvconnections",cmd_srv_enum_conn, "List connections on a server"},
122   {"srvfiles",   cmd_srv_enum_files,   "List files on a server"},
123   {"lsaquery",   cmd_lsa_query_info,   "Query Info Policy (domain member or server)"},
124   {"lookupsids", cmd_lsa_lookup_sids,  "Resolve names from SIDs"},
125   {"enumusers",  cmd_sam_enum_users,   "SAM User Database Query (experimental!)"},
126   {"ntpass",     cmd_sam_ntchange_pwd, "NT SAM Password Change"},
127   {"samuser",    cmd_sam_query_user,   "<username> SAM User Query (experimental!)"},
128   {"samtest",    cmd_sam_test      ,   "SAM User Encrypted RPC test (experimental!)"},
129   {"enumaliases",cmd_sam_enum_aliases, "SAM Aliases Database Query (experimental!)"},
130 #if 0
131   {"enumgroups", cmd_sam_enum_groups,  "SAM Group Database Query (experimental!)"},
132 #endif
133   {"samgroups",  cmd_sam_query_groups, "SAM Group Database Query (experimental!)"},
134   {"quit",       cmd_quit,        "logoff the server"},
135   {"q",          cmd_quit,        "logoff the server"},
136   {"exit",       cmd_quit,        "logoff the server"},
137   {"bye",        cmd_quit,        "logoff the server"},
138   {"help",       cmd_help,        "[command] give help on a command"},
139   {"?",          cmd_help,        "[command] give help on a command"},
140   {"!",          NULL,            "run a shell command on the local system"},
141   {"",           NULL,            NULL}
142 };
143
144
145 /****************************************************************************
146 do a (presumably graceful) quit...
147 ****************************************************************************/
148 static void cmd_quit(struct client_info *info)
149 {
150         rpcclient_stop();
151 #ifdef MEM_MAN
152         {
153                 extern FILE* dbf;
154                 smb_mem_write_status(dbf);
155                 smb_mem_write_errors(dbf);
156                 smb_mem_write_verbose(dbf);
157         }
158 #endif
159         exit(0);
160 }
161
162 /****************************************************************************
163 help
164 ****************************************************************************/
165 static void cmd_help(struct client_info *info)
166 {
167   int i=0,j;
168   fstring buf;
169
170   if (next_token(NULL,buf,NULL, sizeof(buf)))
171     {
172       if ((i = process_tok(buf)) >= 0)
173         fprintf(out_hnd, "HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);                    
174     }
175   else
176     while (commands[i].description)
177       {
178         for (j=0; commands[i].description && (j<5); j++) {
179           fprintf(out_hnd, "%-15s",commands[i].name);
180           i++;
181         }
182         fprintf(out_hnd, "\n");
183       }
184 }
185
186 /*******************************************************************
187   lookup a command string in the list of commands, including 
188   abbreviations
189   ******************************************************************/
190 static int process_tok(fstring tok)
191 {
192   int i = 0, matches = 0;
193   int cmd=0;
194   int tok_len = strlen(tok);
195   
196   while (commands[i].fn != NULL)
197     {
198       if (strequal(commands[i].name,tok))
199         {
200           matches = 1;
201           cmd = i;
202           break;
203         }
204       else if (strnequal(commands[i].name, tok, tok_len))
205         {
206           matches++;
207           cmd = i;
208         }
209       i++;
210     }
211   
212   if (matches == 0)
213     return(-1);
214   else if (matches == 1)
215     return(cmd);
216   else
217     return(-2);
218 }
219
220 /****************************************************************************
221 wait for keyboard activity, swallowing network packets
222 ****************************************************************************/
223 static void wait_keyboard(struct cli_state *cli)
224 {
225   fd_set fds;
226   struct timeval timeout;
227   
228   while (1) 
229     {
230       FD_ZERO(&fds);
231       FD_SET(cli->fd,&fds);
232       FD_SET(fileno(stdin),&fds);
233
234       timeout.tv_sec = 20;
235       timeout.tv_usec = 0;
236       sys_select(MAX(cli->fd,fileno(stdin))+1,&fds,&timeout);
237       
238       if (FD_ISSET(fileno(stdin),&fds))
239         return;
240
241       /* We deliberately use receive_smb instead of
242          client_receive_smb as we want to receive
243          session keepalives and then drop them here.
244        */
245       if (FD_ISSET(cli->fd,&fds))
246         receive_smb(cli->fd,cli->inbuf,0);
247     }  
248 }
249
250 /****************************************************************************
251   process commands from the client
252 ****************************************************************************/
253 static void do_command(struct client_info *info, char *tok, char *line)
254 {
255         int i;
256
257         if ((i = process_tok(tok)) >= 0)
258         {
259                 commands[i].fn(info);
260         }
261         else if (i == -2)
262         {
263                 fprintf(out_hnd, "%s: command abbreviation ambiguous\n", CNV_LANG(tok));
264         }
265         else
266         {
267                 fprintf(out_hnd, "%s: command not found\n", CNV_LANG(tok));
268         }
269 }
270
271 /****************************************************************************
272   process commands from the client
273 ****************************************************************************/
274 static BOOL process( struct client_info *info, char *cmd_str)
275 {
276         pstring line;
277         char *cmd = cmd_str;
278
279         if (cmd[0] != '\0') while (cmd[0] != '\0')
280         {
281                 char *p;
282                 fstring tok;
283
284                 if ((p = strchr(cmd, ';')) == 0)
285                 {
286                         strncpy(line, cmd, 999);
287                         line[1000] = '\0';
288                         cmd += strlen(cmd);
289                 }
290                 else
291                 {
292                         if (p - cmd > 999) p = cmd + 999;
293                         strncpy(line, cmd, p - cmd);
294                         line[p - cmd] = '\0';
295                         cmd = p + 1;
296                 }
297
298                 /* input language code to internal one */
299                 CNV_INPUT (line);
300
301                 /* get the first part of the command */
302                 {
303                         char *ptr = line;
304                         if (!next_token(&ptr,tok,NULL, sizeof(tok))) continue;
305                 }
306
307                 do_command(info, tok, line);
308         }
309         else while (!feof(stdin))
310         {
311                 fstring tok;
312
313                 /* display a prompt */
314                 fprintf(out_hnd, "smb: %s> ", CNV_LANG(info->cur_dir));
315                 fflush(out_hnd);
316
317 #ifdef CLIX
318                 line[0] = wait_keyboard(smb_cli);
319                 /* this might not be such a good idea... */
320                 if ( line[0] == EOF)
321                 {
322                         break;
323                 }
324 #else
325                 wait_keyboard(smb_cli);
326 #endif
327
328                 /* and get a response */
329 #ifdef CLIX
330                 fgets( &line[1],999, stdin);
331 #else
332                 if (!fgets(line,1000,stdin))
333                 {
334                         break;
335                 }
336 #endif
337
338                 /* input language code to internal one */
339                 CNV_INPUT (line);
340
341                 /* special case - first char is ! */
342                 if (*line == '!')
343                 {
344                         system(line + 1);
345                         continue;
346                 }
347
348                 fprintf(out_hnd, "%s\n", line);
349
350                 /* get the first part of the command */
351                 {
352                         char *ptr = line;
353                         if (!next_token(&ptr,tok,NULL, sizeof(tok))) continue;
354                 }
355
356                 do_command(info, tok, line);
357         }
358
359         return(True);
360 }
361
362 /****************************************************************************
363 usage on the program
364 ****************************************************************************/
365 static void usage(char *pname)
366 {
367   fprintf(out_hnd, "Usage: %s service <password> [-d debuglevel] [-l log] ",
368            pname);
369
370   fprintf(out_hnd, "\nVersion %s\n",VERSION);
371   fprintf(out_hnd, "\t-d debuglevel         set the debuglevel\n");
372   fprintf(out_hnd, "\t-l log basename.      Basename for log/debug files\n");
373   fprintf(out_hnd, "\t-n netbios name.      Use this name as my netbios name\n");
374   fprintf(out_hnd, "\t-N                    don't ask for a password\n");
375   fprintf(out_hnd, "\t-m max protocol       set the max protocol level\n");
376   fprintf(out_hnd, "\t-I dest IP            use this IP to connect to\n");
377   fprintf(out_hnd, "\t-E                    write messages to stderr instead of stdout\n");
378   fprintf(out_hnd, "\t-U username           set the network username\n");
379   fprintf(out_hnd, "\t-W workgroup          set the workgroup name\n");
380   fprintf(out_hnd, "\t-c command string     execute semicolon separated commands\n");
381   fprintf(out_hnd, "\t-t terminal code      terminal i/o code {sjis|euc|jis7|jis8|junet|hex}\n");
382   fprintf(out_hnd, "\n");
383 }
384
385 enum client_action
386 {
387         CLIENT_NONE,
388         CLIENT_IPC,
389         CLIENT_SVC
390 };
391
392 /****************************************************************************
393   main program
394 ****************************************************************************/
395  int main(int argc,char *argv[])
396 {
397         BOOL interactive = True;
398
399         int opt;
400         extern FILE *dbf;
401         extern char *optarg;
402         extern int optind;
403         static pstring servicesf = CONFIGFILE;
404         pstring term_code;
405         char *p;
406         BOOL got_pass = False;
407         char *cmd_str="";
408         mode_t myumask = 0755;
409         enum client_action cli_action = CLIENT_NONE;
410
411         struct client_info cli_info;
412
413         pstring password; /* local copy only, if one is entered */
414
415         out_hnd = stdout;
416         fstrcpy(debugf, argv[0]);
417
418         rpcclient_init();
419
420 #ifdef KANJI
421         pstrcpy(term_code, KANJI);
422 #else /* KANJI */
423         *term_code = 0;
424 #endif /* KANJI */
425
426         DEBUGLEVEL = 2;
427
428         cli_info.put_total_size = 0;
429         cli_info.put_total_time_ms = 0;
430         cli_info.get_total_size = 0;
431         cli_info.get_total_time_ms = 0;
432
433         cli_info.dir_total = 0;
434         cli_info.newer_than = 0;
435         cli_info.archive_level = 0;
436         cli_info.print_mode = 1;
437
438         cli_info.translation = False;
439         cli_info.recurse_dir = False;
440         cli_info.lowercase = False;
441         cli_info.prompt = True;
442         cli_info.abort_mget = True;
443
444         cli_info.dest_ip.s_addr = 0;
445         cli_info.name_type = 0x20;
446
447         pstrcpy(cli_info.cur_dir , "\\");
448         pstrcpy(cli_info.file_sel, "");
449         pstrcpy(cli_info.base_dir, "");
450         pstrcpy(smb_cli->domain, "");
451         pstrcpy(smb_cli->user_name, "");
452         pstrcpy(cli_info.myhostname, "");
453         pstrcpy(cli_info.dest_host, "");
454
455         pstrcpy(cli_info.svc_type, "A:");
456         pstrcpy(cli_info.share, "");
457         pstrcpy(cli_info.service, "");
458
459         ZERO_STRUCT(cli_info.dom.level3_sid);
460         ZERO_STRUCT(cli_info.dom.level5_sid);
461         fstrcpy(cli_info.dom.level3_dom, "");
462         fstrcpy(cli_info.dom.level5_dom, "");
463
464         smb_cli->nt_pipe_fnum   = 0xffff;
465
466         TimeInit();
467         charset_initialise();
468
469         myumask = umask(0);
470         umask(myumask);
471
472         if (!get_myname(global_myname))
473         {
474                 fprintf(stderr, "Failed to get my hostname.\n");
475         }
476
477         if (getenv("USER"))
478         {
479                 pstrcpy(smb_cli->user_name,getenv("USER"));
480
481                 /* modification to support userid%passwd syntax in the USER var
482                 25.Aug.97, jdblair@uab.edu */
483
484                 if ((p=strchr(smb_cli->user_name,'%')))
485                 {
486                         *p = 0;
487                         pstrcpy(password,p+1);
488                         got_pass = True;
489                         memset(strchr(getenv("USER"),'%')+1,'X',strlen(password));
490                 }
491                 strupper(smb_cli->user_name);
492         }
493
494         password[0] = 0;
495
496         /* modification to support PASSWD environmental var
497            25.Aug.97, jdblair@uab.edu */
498         if (getenv("PASSWD"))
499         {
500                 pstrcpy(password,getenv("PASSWD"));
501         }
502
503         if (*smb_cli->user_name == 0 && getenv("LOGNAME"))
504         {
505                 pstrcpy(smb_cli->user_name,getenv("LOGNAME"));
506                 strupper(smb_cli->user_name);
507         }
508
509         if (argc < 2)
510         {
511                 usage(argv[0]);
512                 exit(1);
513         }
514
515         if (*argv[1] != '-')
516         {
517
518                 pstrcpy(cli_info.service, argv[1]);  
519                 /* Convert any '/' characters in the service name to '\' characters */
520                 string_replace( cli_info.service, '/','\\');
521                 argc--;
522                 argv++;
523
524                 fprintf(out_hnd, "service: %s\n", cli_info.service);
525
526                 if (count_chars(cli_info.service,'\\') < 3)
527                 {
528                         usage(argv[0]);
529                         printf("\n%s: Not enough '\\' characters in service\n", cli_info.service);
530                         exit(1);
531                 }
532
533                 /*
534                 if (count_chars(cli_info.service,'\\') > 3)
535                 {
536                         usage(pname);
537                         printf("\n%s: Too many '\\' characters in service\n", cli_info.service);
538                         exit(1);
539                 }
540                 */
541
542                 if (argc > 1 && (*argv[1] != '-'))
543                 {
544                         got_pass = True;
545                         pstrcpy(password,argv[1]);  
546                         memset(argv[1],'X',strlen(argv[1]));
547                         argc--;
548                         argv++;
549                 }
550
551                 cli_action = CLIENT_SVC;
552         }
553
554         while ((opt = getopt(argc, argv,"s:O:M:S:i:N:n:d:l:hI:EB:U:L:t:m:W:T:D:c:")) != EOF)
555         {
556                 switch (opt)
557                 {
558                         case 'm':
559                         {
560                                 /* FIXME ... max_protocol seems to be funny here */
561
562                                 int max_protocol = 0;
563                                 max_protocol = interpret_protocol(optarg,max_protocol);
564                                 fprintf(stderr, "max protocol not currently supported\n");
565                                 break;
566                         }
567
568                         case 'O':
569                         {
570                                 pstrcpy(user_socket_options,optarg);
571                                 break;  
572                         }
573
574                         case 'S':
575                         {
576                                 pstrcpy(cli_info.dest_host,optarg);
577                                 strupper(cli_info.dest_host);
578                                 cli_action = CLIENT_IPC;
579                                 break;
580                         }
581
582                         case 'i':
583                         {
584                                 pstrcpy(scope, optarg);
585                                 break;
586                         }
587
588                         case 'U':
589                         {
590                                 char *lp;
591                                 pstrcpy(smb_cli->user_name,optarg);
592                                 if ((lp=strchr(smb_cli->user_name,'%')))
593                                 {
594                                         *lp = 0;
595                                         pstrcpy(password,lp+1);
596                                         got_pass = True;
597                                         memset(strchr(optarg,'%')+1,'X',strlen(password));
598                                 }
599                                 break;
600                         }
601
602                         case 'W':
603                         {
604                                 pstrcpy(smb_cli->domain,optarg);
605                                 break;
606                         }
607
608                         case 'E':
609                         {
610                                 dbf = stderr;
611                                 break;
612                         }
613
614                         case 'I':
615                         {
616                                 cli_info.dest_ip = *interpret_addr2(optarg);
617                                 if (zero_ip(cli_info.dest_ip))
618                                 {
619                                         exit(1);
620                                 }
621                                 break;
622                         }
623
624                         case 'n':
625                         {
626                                 fstrcpy(global_myname, optarg);
627                                 break;
628                         }
629
630                         case 'N':
631                         {
632                                 got_pass = True;
633                                 break;
634                         }
635
636                         case 'd':
637                         {
638                                 if (*optarg == 'A')
639                                         DEBUGLEVEL = 10000;
640                                 else
641                                         DEBUGLEVEL = atoi(optarg);
642                                 break;
643                         }
644
645                         case 'l':
646                         {
647                                 slprintf(debugf, sizeof(debugf)-1,
648                                          "%s.client", optarg);
649                                 interactive = False;
650                                 break;
651                         }
652
653                         case 'c':
654                         {
655                                 cmd_str = optarg;
656                                 got_pass = True;
657                                 break;
658                         }
659
660                         case 'h':
661                         {
662                                 usage(argv[0]);
663                                 exit(0);
664                                 break;
665                         }
666
667                         case 's':
668                         {
669                                 pstrcpy(servicesf, optarg);
670                                 break;
671                         }
672
673                         case 't':
674                         {
675                                 pstrcpy(term_code, optarg);
676                                 break;
677                         }
678
679                         default:
680                         {
681                                 usage(argv[0]);
682                                 exit(1);
683                                 break;
684                         }
685                 }
686         }
687
688         setup_logging(debugf, interactive);
689
690         if (cli_action == CLIENT_NONE)
691         {
692                 usage(argv[0]);
693                 exit(1);
694         }
695
696         strupper(global_myname);
697         fstrcpy(cli_info.myhostname, global_myname);
698
699         DEBUG(3,("%s client started (version %s)\n",timestring(False),VERSION));
700
701         if (!lp_load(servicesf,True, False, False))
702         {
703                 fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
704         }
705
706         codepage_initialise(lp_client_code_page());
707
708         if (*smb_cli->domain == 0) pstrcpy(smb_cli->domain,lp_workgroup());
709
710         load_interfaces();
711
712         if (cli_action == CLIENT_IPC)
713         {
714                 pstrcpy(cli_info.share, "IPC$");
715                 pstrcpy(cli_info.svc_type, "IPC");
716         }
717
718         fstrcpy(cli_info.mach_acct, cli_info.myhostname);
719         strupper(cli_info.mach_acct);
720         fstrcat(cli_info.mach_acct, "$");
721
722         /* set the password cache info */
723         if (got_pass)
724         {
725                 if (password[0] == 0)
726                 {
727                         pwd_set_nullpwd(&(smb_cli->pwd));
728                 }
729                 else
730                 {
731                         pwd_make_lm_nt_16(&(smb_cli->pwd), password); /* generate 16 byte hashes */
732                 }
733         }
734         else 
735         {
736                 pwd_read(&(smb_cli->pwd), "Enter Password:", True);
737         }
738
739         /* paranoia: destroy the local copy of the password */
740         memset((char *)password, '\0', sizeof(password)); 
741
742         /* establish connections.  nothing to stop these being re-established. */
743         rpcclient_connect(&cli_info);
744
745         DEBUG(5,("rpcclient_connect: smb_cli->fd:%d\n", smb_cli->fd));
746         if (smb_cli->fd <= 0)
747         {
748                 fprintf(stderr, "warning: connection could not be established to %s<%02x>\n",
749                                  cli_info.dest_host, cli_info.name_type);
750                 fprintf(stderr, "this version of smbclient may crash if you proceed\n");
751                 exit(-1);
752         }
753
754         switch (cli_action)
755         {
756                 case CLIENT_IPC:
757                 {
758                         process(&cli_info, cmd_str);
759                         break;
760                 }
761
762                 default:
763                 {
764                         fprintf(stderr, "unknown client action requested\n");
765                         break;
766                 }
767         }
768
769         rpcclient_stop();
770
771         return(0);
772 }