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