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