r23779: Change from v2 or later to v3 or later.
[gd/samba/.git] / source3 / libsmb / clidfs.c
1 /* 
2    Unix SMB/CIFS implementation.
3    client connect/disconnect routines
4    Copyright (C) Andrew Tridgell                  1994-1998
5    Copyright (C) Gerald (Jerry) Carter            2004
6    Copyright (C) Jeremy Allison                   2007
7       
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24
25 /********************************************************************
26  Important point.
27
28  DFS paths are *always* of the form \server\share\<pathname> (the \ characters
29  are not C escaped here).
30
31  - but if we're using POSIX paths then <pathname> may contain
32    '/' separators, not '\\' separators. So cope with '\\' or '/'
33    as a separator when looking at the pathname part.... JRA.
34 ********************************************************************/
35
36 struct client_connection {
37         struct client_connection *prev, *next;
38         struct cli_state *cli;
39         pstring mount;
40 };
41
42 /* global state....globals reek! */
43
44 static pstring username;
45 static pstring password;
46 static BOOL use_kerberos;
47 static BOOL got_pass;
48 static int signing_state;
49 int max_protocol = PROTOCOL_NT1;
50
51 static int port;
52 static int name_type = 0x20;
53 static BOOL have_ip;
54 static struct in_addr dest_ip;
55
56 static struct client_connection *connections;
57
58 /********************************************************************
59  Return a connection to a server.
60 ********************************************************************/
61
62 static struct cli_state *do_connect( const char *server, const char *share,
63                                      BOOL show_sessetup )
64 {
65         struct cli_state *c = NULL;
66         struct nmb_name called, calling;
67         const char *server_n;
68         struct in_addr ip;
69         pstring servicename;
70         char *sharename;
71         fstring newserver, newshare;
72         NTSTATUS status;
73         
74         /* make a copy so we don't modify the global string 'service' */
75         pstrcpy(servicename, share);
76         sharename = servicename;
77         if (*sharename == '\\') {
78                 server = sharename+2;
79                 sharename = strchr_m(server,'\\');
80                 if (!sharename) return NULL;
81                 *sharename = 0;
82                 sharename++;
83         }
84
85         server_n = server;
86         
87         zero_ip(&ip);
88
89         make_nmb_name(&calling, global_myname(), 0x0);
90         make_nmb_name(&called , server, name_type);
91
92  again:
93         zero_ip(&ip);
94         if (have_ip) 
95                 ip = dest_ip;
96
97         /* have to open a new connection */
98         if (!(c=cli_initialise()) || (cli_set_port(c, port) != port)) {
99                 d_printf("Connection to %s failed\n", server_n);
100                 return NULL;
101         }
102         status = cli_connect(c, server_n, &ip);
103         if (!NT_STATUS_IS_OK(status)) {
104                 d_printf("Connection to %s failed (Error %s)\n", server_n, nt_errstr(status));
105                 return NULL;
106         }
107
108         c->protocol = max_protocol;
109         c->use_kerberos = use_kerberos;
110         cli_setup_signing_state(c, signing_state);
111                 
112
113         if (!cli_session_request(c, &calling, &called)) {
114                 char *p;
115                 d_printf("session request to %s failed (%s)\n", 
116                          called.name, cli_errstr(c));
117                 cli_shutdown(c);
118                 c = NULL;
119                 if ((p=strchr_m(called.name, '.'))) {
120                         *p = 0;
121                         goto again;
122                 }
123                 if (strcmp(called.name, "*SMBSERVER")) {
124                         make_nmb_name(&called , "*SMBSERVER", 0x20);
125                         goto again;
126                 }
127                 return NULL;
128         }
129
130         DEBUG(4,(" session request ok\n"));
131
132         if (!cli_negprot(c)) {
133                 d_printf("protocol negotiation failed\n");
134                 cli_shutdown(c);
135                 return NULL;
136         }
137
138         if (!got_pass) {
139                 char *pass = getpass("Password: ");
140                 if (pass) {
141                         pstrcpy(password, pass);
142                         got_pass = 1;
143                 }
144         }
145
146         if (!NT_STATUS_IS_OK(cli_session_setup(c, username, 
147                                                password, strlen(password),
148                                                password, strlen(password),
149                                                lp_workgroup()))) {
150                 /* if a password was not supplied then try again with a null username */
151                 if (password[0] || !username[0] || use_kerberos ||
152                     !NT_STATUS_IS_OK(cli_session_setup(c, "", "", 0, "", 0,
153                                                        lp_workgroup()))) { 
154                         d_printf("session setup failed: %s\n", cli_errstr(c));
155                         if (NT_STATUS_V(cli_nt_error(c)) == 
156                             NT_STATUS_V(NT_STATUS_MORE_PROCESSING_REQUIRED))
157                                 d_printf("did you forget to run kinit?\n");
158                         cli_shutdown(c);
159                         return NULL;
160                 }
161                 d_printf("Anonymous login successful\n");
162         }
163
164         if ( show_sessetup ) {
165                 if (*c->server_domain) {
166                         DEBUG(0,("Domain=[%s] OS=[%s] Server=[%s]\n",
167                                 c->server_domain,c->server_os,c->server_type));
168                 } else if (*c->server_os || *c->server_type){
169                         DEBUG(0,("OS=[%s] Server=[%s]\n",
170                                  c->server_os,c->server_type));
171                 }               
172         }
173         DEBUG(4,(" session setup ok\n"));
174
175         /* here's the fun part....to support 'msdfs proxy' shares
176            (on Samba or windows) we have to issues a TRANS_GET_DFS_REFERRAL 
177            here before trying to connect to the original share.
178            check_dfs_proxy() will fail if it is a normal share. */
179
180         if ( (c->capabilities & CAP_DFS) && cli_check_msdfs_proxy( c, sharename, newserver, newshare ) ) {
181                 cli_shutdown(c);
182                 return do_connect( newserver, newshare, False );
183         }
184
185         /* must be a normal share */
186
187         if (!cli_send_tconX(c, sharename, "?????", password, strlen(password)+1)) {
188                 d_printf("tree connect failed: %s\n", cli_errstr(c));
189                 cli_shutdown(c);
190                 return NULL;
191         }
192
193         DEBUG(4,(" tconx ok\n"));
194
195         return c;
196 }
197
198 /****************************************************************************
199 ****************************************************************************/
200
201 static void cli_cm_set_mntpoint( struct cli_state *c, const char *mnt )
202 {
203         struct client_connection *p;
204         int i;
205
206         for ( p=connections,i=0; p; p=p->next,i++ ) {
207                 if ( strequal(p->cli->desthost, c->desthost) && strequal(p->cli->share, c->share) )
208                         break;
209         }
210         
211         if ( p ) {
212                 pstrcpy( p->mount, mnt );
213                 clean_name(p->mount);
214         }
215 }
216
217 /****************************************************************************
218 ****************************************************************************/
219
220 const char *cli_cm_get_mntpoint( struct cli_state *c )
221 {
222         struct client_connection *p;
223         int i;
224
225         for ( p=connections,i=0; p; p=p->next,i++ ) {
226                 if ( strequal(p->cli->desthost, c->desthost) && strequal(p->cli->share, c->share) )
227                         break;
228         }
229         
230         if ( p )
231                 return p->mount;
232                 
233         return NULL;
234 }
235
236 /********************************************************************
237  Add a new connection to the list
238 ********************************************************************/
239
240 static struct cli_state *cli_cm_connect( const char *server,
241                                         const char *share,
242                                         BOOL show_hdr)
243 {
244         struct client_connection *node;
245         
246         node = SMB_XMALLOC_P( struct client_connection );
247         
248         node->cli = do_connect( server, share, show_hdr );
249
250         if ( !node->cli ) {
251                 SAFE_FREE( node );
252                 return NULL;
253         }
254
255         DLIST_ADD( connections, node );
256
257         cli_cm_set_mntpoint( node->cli, "" );
258
259         return node->cli;
260
261 }
262
263 /********************************************************************
264  Return a connection to a server.
265 ********************************************************************/
266
267 static struct cli_state *cli_cm_find( const char *server, const char *share )
268 {
269         struct client_connection *p;
270
271         for ( p=connections; p; p=p->next ) {
272                 if ( strequal(server, p->cli->desthost) && strequal(share,p->cli->share) )
273                         return p->cli;
274         }
275
276         return NULL;
277 }
278
279 /****************************************************************************
280  open a client connection to a \\server\share.  Set's the current *cli 
281  global variable as a side-effect (but only if the connection is successful).
282 ****************************************************************************/
283
284 struct cli_state *cli_cm_open(const char *server,
285                                 const char *share,
286                                 BOOL show_hdr)
287 {
288         struct cli_state *c;
289         
290         /* try to reuse an existing connection */
291
292         c = cli_cm_find( server, share );
293         
294         if ( !c ) {
295                 c = cli_cm_connect(server, share, show_hdr);
296         }
297
298         return c;
299 }
300
301 /****************************************************************************
302 ****************************************************************************/
303
304 void cli_cm_shutdown( void )
305 {
306
307         struct client_connection *p, *x;
308
309         for ( p=connections; p; ) {
310                 cli_shutdown( p->cli );
311                 x = p;
312                 p = p->next;
313
314                 SAFE_FREE( x );
315         }
316
317         connections = NULL;
318         return;
319 }
320
321 /****************************************************************************
322 ****************************************************************************/
323
324 void cli_cm_display(void)
325 {
326         struct client_connection *p;
327         int i;
328
329         for ( p=connections,i=0; p; p=p->next,i++ ) {
330                 d_printf("%d:\tserver=%s, share=%s\n", 
331                         i, p->cli->desthost, p->cli->share );
332         }
333 }
334
335 /****************************************************************************
336 ****************************************************************************/
337
338 void cli_cm_set_credentials( struct user_auth_info *user )
339 {
340         pstrcpy( username, user->username );
341         
342         if ( user->got_pass ) {
343                 pstrcpy( password, user->password );
344                 got_pass = True;
345         }
346         
347         use_kerberos = user->use_kerberos;      
348         signing_state = user->signing_state;
349 }
350
351 /****************************************************************************
352 ****************************************************************************/
353
354 void cli_cm_set_port( int port_number )
355 {
356         port = port_number;
357 }
358
359 /****************************************************************************
360 ****************************************************************************/
361
362 void cli_cm_set_dest_name_type( int type )
363 {
364         name_type = type;
365 }
366
367 /****************************************************************************
368 ****************************************************************************/
369
370 void cli_cm_set_dest_ip(struct in_addr ip )
371 {
372         dest_ip = ip;
373         have_ip = True;
374 }
375
376 /**********************************************************************
377  split a dfs path into the server, share name, and extrapath components
378 **********************************************************************/
379
380 static void split_dfs_path( const char *nodepath, fstring server, fstring share, pstring extrapath )
381 {
382         char *p, *q;
383         pstring path;
384
385         pstrcpy( path, nodepath );
386
387         if ( path[0] != '\\' ) {
388                 return;
389         }
390
391         p = strchr_m( path + 1, '\\' );
392         if ( !p ) {
393                 return;
394         }
395
396         *p = '\0';
397         p++;
398
399         /* Look for any extra/deep path */
400         q = strchr_m(p, '\\');
401         if (q != NULL) {
402                 *q = '\0';
403                 q++;
404                 pstrcpy( extrapath, q );
405         } else {
406                 pstrcpy( extrapath, '\0' );
407         }
408         
409         fstrcpy( share, p );
410         fstrcpy( server, &path[1] );
411 }
412
413 /****************************************************************************
414  Return the original path truncated at the directory component before
415  the first wildcard character. Trust the caller to provide a NULL 
416  terminated string
417 ****************************************************************************/
418
419 static void clean_path(const char *path, pstring path_out)
420 {
421         size_t len;
422         char *p1, *p2, *p;
423                 
424         /* No absolute paths. */
425         while (IS_DIRECTORY_SEP(*path)) {
426                 path++;
427         }
428
429         pstrcpy(path_out, path);
430
431         p1 = strchr_m(path_out, '*');
432         p2 = strchr_m(path_out, '?');
433
434         if (p1 || p2) {
435                 if (p1 && p2) {
436                         p = MIN(p1,p2);
437                 } else if (!p1) {
438                         p = p2;
439                 } else {
440                         p = p1;
441                 }
442                 *p = '\0';
443
444                 /* Now go back to the start of this component. */
445                 p1 = strrchr_m(path_out, '/');
446                 p2 = strrchr_m(path_out, '\\');
447                 p = MAX(p1,p2);
448                 if (p) {
449                         *p = '\0';
450                 }
451         }
452
453         /* Strip any trailing separator */
454
455         len = strlen(path_out);
456         if ( (len > 0) && IS_DIRECTORY_SEP(path_out[len-1])) {
457                 path_out[len-1] = '\0';
458         }
459 }
460
461 /****************************************************************************
462 ****************************************************************************/
463
464 static void cli_dfs_make_full_path( struct cli_state *cli,
465                                         const char *dir,
466                                         pstring path_out)
467 {
468         /* Ensure the extrapath doesn't start with a separator. */
469         while (IS_DIRECTORY_SEP(*dir)) {
470                 dir++;
471         }
472
473         pstr_sprintf( path_out, "\\%s\\%s\\%s", cli->desthost, cli->share, dir);
474 }
475
476 /********************************************************************
477  check for dfs referral
478 ********************************************************************/
479
480 static BOOL cli_dfs_check_error( struct cli_state *cli, NTSTATUS status )
481 {
482         uint32 flgs2 = SVAL(cli->inbuf,smb_flg2);
483
484         /* only deal with DS when we negotiated NT_STATUS codes and UNICODE */
485
486         if ( !( (flgs2&FLAGS2_32_BIT_ERROR_CODES) && (flgs2&FLAGS2_UNICODE_STRINGS) ) )
487                 return False;
488
489         if ( NT_STATUS_EQUAL( status, NT_STATUS(IVAL(cli->inbuf,smb_rcls)) ) )
490                 return True;
491
492         return False;
493 }
494
495 /********************************************************************
496  get the dfs referral link
497 ********************************************************************/
498
499 BOOL cli_dfs_get_referral( struct cli_state *cli,
500                         const char *path, 
501                         CLIENT_DFS_REFERRAL**refs,
502                         size_t *num_refs,
503                         uint16 *consumed)
504 {
505         unsigned int data_len = 0;
506         unsigned int param_len = 0;
507         uint16 setup = TRANSACT2_GET_DFS_REFERRAL;
508         char param[sizeof(pstring)+2];
509         pstring data;
510         char *rparam=NULL, *rdata=NULL;
511         char *p;
512         size_t pathlen = 2*(strlen(path)+1);
513         uint16 num_referrals;
514         CLIENT_DFS_REFERRAL *referrals = NULL;
515         
516         memset(param, 0, sizeof(param));
517         SSVAL(param, 0, 0x03);  /* max referral level */
518         p = &param[2];
519
520         p += clistr_push(cli, p, path, MIN(pathlen, sizeof(param)-2), STR_TERMINATE);
521         param_len = PTR_DIFF(p, param);
522
523         if (!cli_send_trans(cli, SMBtrans2,
524                 NULL,                        /* name */
525                 -1, 0,                          /* fid, flags */
526                 &setup, 1, 0,                   /* setup, length, max */
527                 param, param_len, 2,            /* param, length, max */
528                 (char *)&data,  data_len, cli->max_xmit /* data, length, max */
529                 )) {
530                         return False;
531         }
532
533         if (!cli_receive_trans(cli, SMBtrans2,
534                 &rparam, &param_len,
535                 &rdata, &data_len)) {
536                         return False;
537         }
538         
539         *consumed     = SVAL( rdata, 0 );
540         num_referrals = SVAL( rdata, 2 );
541         
542         if ( num_referrals != 0 ) {
543                 uint16 ref_version;
544                 uint16 ref_size;
545                 int i;
546                 uint16 node_offset;
547
548                 referrals = SMB_XMALLOC_ARRAY( CLIENT_DFS_REFERRAL, num_referrals );
549
550                 /* start at the referrals array */
551         
552                 p = rdata+8;
553                 for ( i=0; i<num_referrals; i++ ) {
554                         ref_version = SVAL( p, 0 );
555                         ref_size    = SVAL( p, 2 );
556                         node_offset = SVAL( p, 16 );
557                         
558                         if ( ref_version != 3 ) {
559                                 p += ref_size;
560                                 continue;
561                         }
562                         
563                         referrals[i].proximity = SVAL( p, 8 );
564                         referrals[i].ttl       = SVAL( p, 10 );
565
566                         clistr_pull( cli, referrals[i].dfspath, p+node_offset, 
567                                 sizeof(referrals[i].dfspath), -1, STR_TERMINATE|STR_UNICODE );
568
569                         p += ref_size;
570                 }
571         }
572         
573         *num_refs = num_referrals;
574         *refs = referrals;
575
576         SAFE_FREE(rdata);
577         SAFE_FREE(rparam);
578
579         return True;
580 }
581
582
583 /********************************************************************
584 ********************************************************************/
585
586 BOOL cli_resolve_path( const char *mountpt,
587                         struct cli_state *rootcli,
588                         const char *path,
589                         struct cli_state **targetcli,
590                         pstring targetpath)
591 {
592         CLIENT_DFS_REFERRAL *refs = NULL;
593         size_t num_refs;
594         uint16 consumed;
595         struct cli_state *cli_ipc;
596         pstring dfs_path, cleanpath, extrapath;
597         int pathlen;
598         fstring server, share;
599         struct cli_state *newcli;
600         pstring newpath;
601         pstring newmount;
602         char *ppath, *temppath = NULL;
603         
604         SMB_STRUCT_STAT sbuf;
605         uint32 attributes;
606         
607         if ( !rootcli || !path || !targetcli ) {
608                 return False;
609         }
610                 
611         /* Don't do anything if this is not a DFS root. */
612
613         if ( !rootcli->dfsroot) {
614                 *targetcli = rootcli;
615                 pstrcpy( targetpath, path );
616                 return True;
617         }
618
619         *targetcli = NULL;
620
621         /* Send a trans2_query_path_info to check for a referral. */
622
623         clean_path(path, cleanpath);
624         cli_dfs_make_full_path(rootcli, cleanpath, dfs_path );
625
626         if (cli_qpathinfo_basic( rootcli, dfs_path, &sbuf, &attributes ) ) {
627                 /* This is an ordinary path, just return it. */
628                 *targetcli = rootcli;
629                 pstrcpy( targetpath, path );
630                 goto done;
631         }
632
633         /* Special case where client asked for a path that does not exist */
634
635         if ( cli_dfs_check_error(rootcli, NT_STATUS_OBJECT_NAME_NOT_FOUND) ) {
636                 *targetcli = rootcli;
637                 pstrcpy( targetpath, path );
638                 goto done;
639         }
640
641         /* We got an error, check for DFS referral. */
642
643         if ( !cli_dfs_check_error(rootcli, NT_STATUS_PATH_NOT_COVERED))  {
644                 return False;
645         }
646
647         /* Check for the referral. */
648
649         if ( !(cli_ipc = cli_cm_open( rootcli->desthost, "IPC$", False )) ) {
650                 return False;
651         }
652         
653         if ( !cli_dfs_get_referral(cli_ipc, dfs_path, &refs, &num_refs, &consumed) 
654                         || !num_refs ) {
655                 return False;
656         }
657         
658         /* Just store the first referral for now. */
659
660         split_dfs_path( refs[0].dfspath, server, share, extrapath );
661         SAFE_FREE(refs);
662
663         /* Make sure to recreate the original string including any wildcards. */
664         
665         cli_dfs_make_full_path( rootcli, path, dfs_path);
666         pathlen = strlen( dfs_path )*2;
667         consumed = MIN(pathlen, consumed );
668         pstrcpy( targetpath, &dfs_path[consumed/2] );
669         dfs_path[consumed/2] = '\0';
670
671         /*
672          * targetpath is now the unconsumed part of the path.
673          * dfs_path is now the consumed part of the path (in \server\share\path format).
674          */
675
676         /* Open the connection to the target server & share */
677         
678         if ( (*targetcli = cli_cm_open(server, share, False)) == NULL ) {
679                 d_printf("Unable to follow dfs referral [\\%s\\%s]\n",
680                         server, share );
681                 return False;
682         }
683         
684         if (strlen(extrapath) > 0) {
685                 string_append(&temppath, extrapath);
686                 string_append(&temppath, targetpath);
687                 pstrcpy( targetpath, temppath );
688         }
689         
690         /* parse out the consumed mount path */
691         /* trim off the \server\share\ */
692
693         ppath = dfs_path;
694
695         if (*ppath != '\\') {
696                 d_printf("cli_resolve_path: dfs_path (%s) not in correct format.\n",
697                         dfs_path );
698                 return False;
699         }
700
701         ppath++; /* Now pointing at start of server name. */
702         
703         if ((ppath = strchr_m( dfs_path, '\\' )) == NULL) {
704                 return False;
705         }
706
707         ppath++; /* Now pointing at start of share name. */
708
709         if ((ppath = strchr_m( ppath+1, '\\' )) == NULL) {
710                 return False;
711         }
712
713         ppath++; /* Now pointing at path component. */
714
715         pstr_sprintf( newmount, "%s\\%s", mountpt, ppath );
716
717         cli_cm_set_mntpoint( *targetcli, newmount );
718
719         /* Check for another dfs referral, note that we are not 
720            checking for loops here. */
721
722         if ( !strequal( targetpath, "\\" ) &&  !strequal( targetpath, "/")) {
723                 if ( cli_resolve_path( newmount, *targetcli, targetpath, &newcli, newpath ) ) {
724                         /*
725                          * When cli_resolve_path returns true here it's always
726                          * returning the complete path in newpath, so we're done
727                          * here.
728                          */
729                         *targetcli = newcli;
730                         pstrcpy( targetpath, newpath );
731                         return True;
732                 }
733         }
734
735   done:
736
737         /* If returning True ensure we return a dfs root full path. */
738         if ( (*targetcli)->dfsroot ) {
739                 pstrcpy(dfs_path, targetpath );
740                 cli_dfs_make_full_path( *targetcli, dfs_path, targetpath); 
741         }
742
743         return True;
744 }
745
746 /********************************************************************
747 ********************************************************************/
748
749 BOOL cli_check_msdfs_proxy( struct cli_state *cli, const char *sharename,
750                             fstring newserver, fstring newshare )
751 {
752         CLIENT_DFS_REFERRAL *refs = NULL;
753         size_t num_refs;
754         uint16 consumed;
755         pstring fullpath;
756         BOOL res;
757         uint16 cnum;
758         pstring newextrapath;
759         
760         if ( !cli || !sharename )
761                 return False;
762
763         cnum = cli->cnum;
764
765         /* special case.  never check for a referral on the IPC$ share */
766
767         if ( strequal( sharename, "IPC$" ) ) {
768                 return False;
769         }
770                 
771         /* send a trans2_query_path_info to check for a referral */
772         
773         pstr_sprintf( fullpath, "\\%s\\%s", cli->desthost, sharename );
774
775         /* check for the referral */
776
777         if (!cli_send_tconX(cli, "IPC$", "IPC", NULL, 0)) {
778                 return False;
779         }
780
781         res = cli_dfs_get_referral(cli, fullpath, &refs, &num_refs, &consumed);
782
783         if (!cli_tdis(cli)) {
784                 SAFE_FREE( refs );
785                 return False;
786         }
787
788         cli->cnum = cnum;
789
790         if (!res || !num_refs ) {
791                 SAFE_FREE( refs );
792                 return False;
793         }
794         
795         split_dfs_path( refs[0].dfspath, newserver, newshare, newextrapath );
796
797         /* check that this is not a self-referral */
798
799         if ( strequal( cli->desthost, newserver ) && strequal( sharename, newshare ) ) {
800                 SAFE_FREE( refs );
801                 return False;
802         }
803         
804         SAFE_FREE( refs );
805         
806         return True;
807 }