6abc4071e51a6013b168dce6249ca46cf3ccb7ae
[samba.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         bzero(smb_cli, 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   {"lookupnames",cmd_lsa_lookup_names,  "Resolve SIDs from names"},
126   {"enumusers",  cmd_sam_enum_users,   "SAM User Database Query (experimental!)"},
127   {"creategroup",cmd_sam_create_dom_group,"SAM Create Domain Group"},
128   {"ntpass",     cmd_sam_ntchange_pwd, "NT SAM Password Change"},
129   {"samuser",    cmd_sam_query_user,   "<username> SAM User Query (experimental!)"},
130   {"samtest",    cmd_sam_test      ,   "SAM User Encrypted RPC test (experimental!)"},
131   {"enumaliases",cmd_sam_enum_aliases, "SAM Aliases Database Query (experimental!)"},
132 #if 0
133   {"enumgroups", cmd_sam_enum_groups,  "SAM Group Database Query (experimental!)"},
134 #endif
135   {"samgroups",  cmd_sam_query_groups, "SAM Group Database Query (experimental!)"},
136   {"quit",       cmd_quit,        "logoff the server"},
137   {"q",          cmd_quit,        "logoff the server"},
138   {"exit",       cmd_quit,        "logoff the server"},
139   {"bye",        cmd_quit,        "logoff the server"},
140   {"help",       cmd_help,        "[command] give help on a command"},
141   {"?",          cmd_help,        "[command] give help on a command"},
142   {"!",          NULL,            "run a shell command on the local system"},
143   {"",           NULL,            NULL}
144 };
145
146
147 /****************************************************************************
148 do a (presumably graceful) quit...
149 ****************************************************************************/
150 static void cmd_quit(struct client_info *info)
151 {
152         rpcclient_stop();
153 #ifdef MEM_MAN
154         {
155                 extern FILE* dbf;
156                 smb_mem_write_status(dbf);
157                 smb_mem_write_errors(dbf);
158                 smb_mem_write_verbose(dbf);
159         }
160 #endif
161         exit(0);
162 }
163
164 /****************************************************************************
165 help
166 ****************************************************************************/
167 static void cmd_help(struct client_info *info)
168 {
169   int i=0,j;
170   fstring buf;
171
172   if (next_token(NULL,buf,NULL, sizeof(buf)))
173     {
174       if ((i = process_tok(buf)) >= 0)
175         fprintf(out_hnd, "HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);                    
176     }
177   else
178     while (commands[i].description)
179       {
180         for (j=0; commands[i].description && (j<5); j++) {
181           fprintf(out_hnd, "%-15s",commands[i].name);
182           i++;
183         }
184         fprintf(out_hnd, "\n");
185       }
186 }
187
188 /*******************************************************************
189   lookup a command string in the list of commands, including 
190   abbreviations
191   ******************************************************************/
192 static int process_tok(fstring tok)
193 {
194   int i = 0, matches = 0;
195   int cmd=0;
196   int tok_len = strlen(tok);
197   
198   while (commands[i].fn != NULL)
199     {
200       if (strequal(commands[i].name,tok))
201         {
202           matches = 1;
203           cmd = i;
204           break;
205         }
206       else if (strnequal(commands[i].name, tok, tok_len))
207         {
208           matches++;
209           cmd = i;
210         }
211       i++;
212     }
213   
214   if (matches == 0)
215     return(-1);
216   else if (matches == 1)
217     return(cmd);
218   else
219     return(-2);
220 }
221
222 /****************************************************************************
223 wait for keyboard activity, swallowing network packets
224 ****************************************************************************/
225 static void wait_keyboard(struct cli_state *cli)
226 {
227   fd_set fds;
228   struct timeval timeout;
229   
230   while (1) 
231     {
232       FD_ZERO(&fds);
233       FD_SET(cli->fd,&fds);
234       FD_SET(fileno(stdin),&fds);
235
236       timeout.tv_sec = 20;
237       timeout.tv_usec = 0;
238       sys_select(MAX(cli->fd,fileno(stdin))+1,&fds,&timeout);
239       
240       if (FD_ISSET(fileno(stdin),&fds))
241         return;
242
243       /* We deliberately use receive_smb instead of
244          client_receive_smb as we want to receive
245          session keepalives and then drop them here.
246        */
247       if (FD_ISSET(cli->fd,&fds))
248         receive_smb(cli->fd,cli->inbuf,0);
249     }  
250 }
251
252 /****************************************************************************
253   process commands from the client
254 ****************************************************************************/
255 static void do_command(struct client_info *info, char *tok, char *line)
256 {
257         int i;
258
259         if ((i = process_tok(tok)) >= 0)
260         {
261                 commands[i].fn(info);
262         }
263         else if (i == -2)
264         {
265                 fprintf(out_hnd, "%s: command abbreviation ambiguous\n", CNV_LANG(tok));
266         }
267         else
268         {
269                 fprintf(out_hnd, "%s: command not found\n", CNV_LANG(tok));
270         }
271 }
272
273 /****************************************************************************
274   process commands from the client
275 ****************************************************************************/
276 static BOOL process( struct client_info *info, char *cmd_str)
277 {
278         pstring line;
279         char *cmd = cmd_str;
280
281         if (cmd[0] != '\0') while (cmd[0] != '\0')
282         {
283                 char *p;
284                 fstring tok;
285
286                 if ((p = strchr(cmd, ';')) == 0)
287                 {
288                         strncpy(line, cmd, 999);
289                         line[1000] = '\0';
290                         cmd += strlen(cmd);
291                 }
292                 else
293                 {
294                         if (p - cmd > 999) p = cmd + 999;
295                         strncpy(line, cmd, p - cmd);
296                         line[p - cmd] = '\0';
297                         cmd = p + 1;
298                 }
299
300                 /* input language code to internal one */
301                 CNV_INPUT (line);
302
303                 /* get the first part of the command */
304                 {
305                         char *ptr = line;
306                         if (!next_token(&ptr,tok,NULL, sizeof(tok))) continue;
307                 }
308
309                 do_command(info, tok, line);
310         }
311         else while (!feof(stdin))
312         {
313                 fstring tok;
314
315                 /* display a prompt */
316                 fprintf(out_hnd, "smb: %s> ", CNV_LANG(info->cur_dir));
317                 fflush(out_hnd);
318
319 #ifdef CLIX
320                 line[0] = wait_keyboard(smb_cli);
321                 /* this might not be such a good idea... */
322                 if ( line[0] == EOF)
323                 {
324                         break;
325                 }
326 #else
327                 wait_keyboard(smb_cli);
328 #endif
329
330                 /* and get a response */
331 #ifdef CLIX
332                 fgets( &line[1],999, stdin);
333 #else
334                 if (!fgets(line,1000,stdin))
335                 {
336                         break;
337                 }
338 #endif
339
340                 /* input language code to internal one */
341                 CNV_INPUT (line);
342
343                 /* special case - first char is ! */
344                 if (*line == '!')
345                 {
346                         system(line + 1);
347                         continue;
348                 }
349
350                 fprintf(out_hnd, "%s\n", line);
351
352                 /* get the first part of the command */
353                 {
354                         char *ptr = line;
355                         if (!next_token(&ptr,tok,NULL, sizeof(tok))) continue;
356                 }
357
358                 do_command(info, tok, line);
359         }
360
361         return(True);
362 }
363
364 /****************************************************************************
365 usage on the program
366 ****************************************************************************/
367 static void usage(char *pname)
368 {
369   fprintf(out_hnd, "Usage: %s service <password> [-d debuglevel] [-l log] ",
370            pname);
371
372   fprintf(out_hnd, "\nVersion %s\n",VERSION);
373   fprintf(out_hnd, "\t-d debuglevel         set the debuglevel\n");
374   fprintf(out_hnd, "\t-l log basename.      Basename for log/debug files\n");
375   fprintf(out_hnd, "\t-n netbios name.      Use this name as my netbios name\n");
376   fprintf(out_hnd, "\t-N                    don't ask for a password\n");
377   fprintf(out_hnd, "\t-m max protocol       set the max protocol level\n");
378   fprintf(out_hnd, "\t-I dest IP            use this IP to connect to\n");
379   fprintf(out_hnd, "\t-E                    write messages to stderr instead of stdout\n");
380   fprintf(out_hnd, "\t-U username           set the network username\n");
381   fprintf(out_hnd, "\t-W workgroup          set the workgroup name\n");
382   fprintf(out_hnd, "\t-c command string     execute semicolon separated commands\n");
383   fprintf(out_hnd, "\t-t terminal code      terminal i/o code {sjis|euc|jis7|jis8|junet|hex}\n");
384   fprintf(out_hnd, "\n");
385 }
386
387 enum client_action
388 {
389         CLIENT_NONE,
390         CLIENT_IPC,
391         CLIENT_SVC
392 };
393
394 /****************************************************************************
395   main program
396 ****************************************************************************/
397  int main(int argc,char *argv[])
398 {
399         BOOL interactive = True;
400
401         int opt;
402         extern FILE *dbf;
403         extern char *optarg;
404         extern int optind;
405         static pstring servicesf = CONFIGFILE;
406         pstring term_code;
407         char *p;
408         BOOL got_pass = False;
409         char *cmd_str="";
410         mode_t myumask = 0755;
411         enum client_action cli_action = CLIENT_NONE;
412
413         struct client_info cli_info;
414
415         pstring password; /* local copy only, if one is entered */
416
417         out_hnd = stdout;
418         fstrcpy(debugf, argv[0]);
419
420         rpcclient_init();
421
422 #ifdef KANJI
423         pstrcpy(term_code, KANJI);
424 #else /* KANJI */
425         *term_code = 0;
426 #endif /* KANJI */
427
428         DEBUGLEVEL = 2;
429
430         cli_info.put_total_size = 0;
431         cli_info.put_total_time_ms = 0;
432         cli_info.get_total_size = 0;
433         cli_info.get_total_time_ms = 0;
434
435         cli_info.dir_total = 0;
436         cli_info.newer_than = 0;
437         cli_info.archive_level = 0;
438         cli_info.print_mode = 1;
439
440         cli_info.translation = False;
441         cli_info.recurse_dir = False;
442         cli_info.lowercase = False;
443         cli_info.prompt = True;
444         cli_info.abort_mget = True;
445
446         cli_info.dest_ip.s_addr = 0;
447         cli_info.name_type = 0x20;
448
449         pstrcpy(cli_info.cur_dir , "\\");
450         pstrcpy(cli_info.file_sel, "");
451         pstrcpy(cli_info.base_dir, "");
452         pstrcpy(smb_cli->domain, "");
453         pstrcpy(smb_cli->user_name, "");
454         pstrcpy(cli_info.myhostname, "");
455         pstrcpy(cli_info.dest_host, "");
456
457         pstrcpy(cli_info.svc_type, "A:");
458         pstrcpy(cli_info.share, "");
459         pstrcpy(cli_info.service, "");
460
461         ZERO_STRUCT(cli_info.dom.level3_sid);
462         ZERO_STRUCT(cli_info.dom.level5_sid);
463         fstrcpy(cli_info.dom.level3_dom, "");
464         fstrcpy(cli_info.dom.level5_dom, "");
465
466         smb_cli->nt_pipe_fnum   = 0xffff;
467
468         TimeInit();
469         charset_initialise();
470
471         myumask = umask(0);
472         umask(myumask);
473
474         if (!get_myname(global_myname, NULL))
475         {
476                 fprintf(stderr, "Failed to get my hostname.\n");
477         }
478
479         if (getenv("USER"))
480         {
481                 pstrcpy(smb_cli->user_name,getenv("USER"));
482
483                 /* modification to support userid%passwd syntax in the USER var
484                 25.Aug.97, jdblair@uab.edu */
485
486                 if ((p=strchr(smb_cli->user_name,'%')))
487                 {
488                         *p = 0;
489                         pstrcpy(password,p+1);
490                         got_pass = True;
491                         memset(strchr(getenv("USER"),'%')+1,'X',strlen(password));
492                 }
493                 strupper(smb_cli->user_name);
494         }
495
496         password[0] = 0;
497
498         /* modification to support PASSWD environmental var
499            25.Aug.97, jdblair@uab.edu */
500         if (getenv("PASSWD"))
501         {
502                 pstrcpy(password,getenv("PASSWD"));
503         }
504
505         if (*smb_cli->user_name == 0 && getenv("LOGNAME"))
506         {
507                 pstrcpy(smb_cli->user_name,getenv("LOGNAME"));
508                 strupper(smb_cli->user_name);
509         }
510
511         if (argc < 2)
512         {
513                 usage(argv[0]);
514                 exit(1);
515         }
516
517         if (*argv[1] != '-')
518         {
519
520                 pstrcpy(cli_info.service, argv[1]);  
521                 /* Convert any '/' characters in the service name to '\' characters */
522                 string_replace( cli_info.service, '/','\\');
523                 argc--;
524                 argv++;
525
526                 fprintf(out_hnd, "service: %s\n", cli_info.service);
527
528                 if (count_chars(cli_info.service,'\\') < 3)
529                 {
530                         usage(argv[0]);
531                         printf("\n%s: Not enough '\\' characters in service\n", cli_info.service);
532                         exit(1);
533                 }
534
535                 /*
536                 if (count_chars(cli_info.service,'\\') > 3)
537                 {
538                         usage(pname);
539                         printf("\n%s: Too many '\\' characters in service\n", cli_info.service);
540                         exit(1);
541                 }
542                 */
543
544                 if (argc > 1 && (*argv[1] != '-'))
545                 {
546                         got_pass = True;
547                         pstrcpy(password,argv[1]);  
548                         memset(argv[1],'X',strlen(argv[1]));
549                         argc--;
550                         argv++;
551                 }
552
553                 cli_action = CLIENT_SVC;
554         }
555
556         while ((opt = getopt(argc, argv,"s:B:O:M:S:i:N:n:d:l:hI:EB:U:L:t:m:W:T:D:c:")) != EOF)
557         {
558                 switch (opt)
559                 {
560                         case 'm':
561                         {
562                                 /* FIXME ... max_protocol seems to be funny here */
563
564                                 int max_protocol = 0;
565                                 max_protocol = interpret_protocol(optarg,max_protocol);
566                                 fprintf(stderr, "max protocol not currently supported\n");
567                                 break;
568                         }
569
570                         case 'O':
571                         {
572                                 pstrcpy(user_socket_options,optarg);
573                                 break;  
574                         }
575
576                         case 'S':
577                         {
578                                 pstrcpy(cli_info.dest_host,optarg);
579                                 strupper(cli_info.dest_host);
580                                 cli_action = CLIENT_IPC;
581                                 break;
582                         }
583
584                         case 'B':
585                         {
586                                 iface_set_default(NULL,optarg,NULL);
587                                 break;
588                         }
589
590                         case 'i':
591                         {
592                                 pstrcpy(scope, optarg);
593                                 break;
594                         }
595
596                         case 'U':
597                         {
598                                 char *lp;
599                                 pstrcpy(smb_cli->user_name,optarg);
600                                 if ((lp=strchr(smb_cli->user_name,'%')))
601                                 {
602                                         *lp = 0;
603                                         pstrcpy(password,lp+1);
604                                         got_pass = True;
605                                         memset(strchr(optarg,'%')+1,'X',strlen(password));
606                                 }
607                                 break;
608                         }
609
610                         case 'W':
611                         {
612                                 pstrcpy(smb_cli->domain,optarg);
613                                 break;
614                         }
615
616                         case 'E':
617                         {
618                                 dbf = stderr;
619                                 break;
620                         }
621
622                         case 'I':
623                         {
624                                 cli_info.dest_ip = *interpret_addr2(optarg);
625                                 if (zero_ip(cli_info.dest_ip))
626                                 {
627                                         exit(1);
628                                 }
629                                 break;
630                         }
631
632                         case 'n':
633                         {
634                                 fstrcpy(global_myname, optarg);
635                                 break;
636                         }
637
638                         case 'N':
639                         {
640                                 got_pass = True;
641                                 break;
642                         }
643
644                         case 'd':
645                         {
646                                 if (*optarg == 'A')
647                                         DEBUGLEVEL = 10000;
648                                 else
649                                         DEBUGLEVEL = atoi(optarg);
650                                 break;
651                         }
652
653                         case 'l':
654                         {
655                                 slprintf(debugf, sizeof(debugf)-1,
656                                          "%s.client", optarg);
657                                 interactive = False;
658                                 break;
659                         }
660
661                         case 'c':
662                         {
663                                 cmd_str = optarg;
664                                 got_pass = True;
665                                 break;
666                         }
667
668                         case 'h':
669                         {
670                                 usage(argv[0]);
671                                 exit(0);
672                                 break;
673                         }
674
675                         case 's':
676                         {
677                                 pstrcpy(servicesf, optarg);
678                                 break;
679                         }
680
681                         case 't':
682                         {
683                                 pstrcpy(term_code, optarg);
684                                 break;
685                         }
686
687                         default:
688                         {
689                                 usage(argv[0]);
690                                 exit(1);
691                                 break;
692                         }
693                 }
694         }
695
696         setup_logging(debugf, interactive);
697
698         if (cli_action == CLIENT_NONE)
699         {
700                 usage(argv[0]);
701                 exit(1);
702         }
703
704         strupper(global_myname);
705         fstrcpy(cli_info.myhostname, global_myname);
706
707         DEBUG(3,("%s client started (version %s)\n",timestring(),VERSION));
708
709         if (!lp_load(servicesf,True, False, False))
710         {
711                 fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
712         }
713
714         codepage_initialise(lp_client_code_page());
715
716         if (*smb_cli->domain == 0) pstrcpy(smb_cli->domain,lp_workgroup());
717
718         load_interfaces();
719
720         if (cli_action == CLIENT_IPC)
721         {
722                 pstrcpy(cli_info.share, "IPC$");
723                 pstrcpy(cli_info.svc_type, "IPC");
724         }
725
726         fstrcpy(cli_info.mach_acct, cli_info.myhostname);
727         strupper(cli_info.mach_acct);
728         fstrcat(cli_info.mach_acct, "$");
729
730         /* set the password cache info */
731         if (got_pass)
732         {
733                 if (password[0] == 0)
734                 {
735                         pwd_set_nullpwd(&(smb_cli->pwd));
736                 }
737                 else
738                 {
739                         pwd_make_lm_nt_16(&(smb_cli->pwd), password); /* generate 16 byte hashes */
740                 }
741         }
742         else 
743         {
744                 pwd_read(&(smb_cli->pwd), "Enter Password:", True);
745         }
746
747         /* paranoia: destroy the local copy of the password */
748         bzero(password, sizeof(password)); 
749
750         /* establish connections.  nothing to stop these being re-established. */
751         rpcclient_connect(&cli_info);
752
753         DEBUG(5,("rpcclient_connect: smb_cli->fd:%d\n", smb_cli->fd));
754         if (smb_cli->fd <= 0)
755         {
756                 fprintf(stderr, "warning: connection could not be established to %s<%02x>\n",
757                                  cli_info.dest_host, cli_info.name_type);
758                 fprintf(stderr, "this version of smbclient may crash if you proceed\n");
759                 exit(-1);
760         }
761
762         switch (cli_action)
763         {
764                 case CLIENT_IPC:
765                 {
766                         process(&cli_info, cmd_str);
767                         break;
768                 }
769
770                 default:
771                 {
772                         fprintf(stderr, "unknown client action requested\n");
773                         break;
774                 }
775         }
776
777         rpcclient_stop();
778
779         return(0);
780 }