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