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