More pstring removal. This one was tricky. I had to add
[metze/samba/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 sockaddr_storage dest_ss;
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 sockaddr_storage ss;
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_addr(&ss);
87
88         make_nmb_name(&calling, global_myname(), 0x0);
89         make_nmb_name(&called , server, name_type);
90
91  again:
92         zero_addr(&ss);
93         if (have_ip)
94                 ss = dest_ss;
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, &ss);
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                 char *name = clean_name(NULL, p->mount);
212                 if (!name) {
213                         return;
214                 }
215                 pstrcpy( p->mount, name );
216                 TALLOC_FREE(name);
217         }
218 }
219
220 /****************************************************************************
221 ****************************************************************************/
222
223 const char *cli_cm_get_mntpoint( struct cli_state *c )
224 {
225         struct client_connection *p;
226         int i;
227
228         for ( p=connections,i=0; p; p=p->next,i++ ) {
229                 if ( strequal(p->cli->desthost, c->desthost) && strequal(p->cli->share, c->share) )
230                         break;
231         }
232         
233         if ( p )
234                 return p->mount;
235                 
236         return NULL;
237 }
238
239 /********************************************************************
240  Add a new connection to the list
241 ********************************************************************/
242
243 static struct cli_state *cli_cm_connect( const char *server,
244                                         const char *share,
245                                         bool show_hdr)
246 {
247         struct client_connection *node;
248         
249         node = SMB_XMALLOC_P( struct client_connection );
250         
251         node->cli = do_connect( server, share, show_hdr );
252
253         if ( !node->cli ) {
254                 SAFE_FREE( node );
255                 return NULL;
256         }
257
258         DLIST_ADD( connections, node );
259
260         cli_cm_set_mntpoint( node->cli, "" );
261
262         return node->cli;
263
264 }
265
266 /********************************************************************
267  Return a connection to a server.
268 ********************************************************************/
269
270 static struct cli_state *cli_cm_find( const char *server, const char *share )
271 {
272         struct client_connection *p;
273
274         for ( p=connections; p; p=p->next ) {
275                 if ( strequal(server, p->cli->desthost) && strequal(share,p->cli->share) )
276                         return p->cli;
277         }
278
279         return NULL;
280 }
281
282 /****************************************************************************
283  open a client connection to a \\server\share.  Set's the current *cli 
284  global variable as a side-effect (but only if the connection is successful).
285 ****************************************************************************/
286
287 struct cli_state *cli_cm_open(const char *server,
288                                 const char *share,
289                                 bool show_hdr)
290 {
291         struct cli_state *c;
292         
293         /* try to reuse an existing connection */
294
295         c = cli_cm_find( server, share );
296         
297         if ( !c ) {
298                 c = cli_cm_connect(server, share, show_hdr);
299         }
300
301         return c;
302 }
303
304 /****************************************************************************
305 ****************************************************************************/
306
307 void cli_cm_shutdown( void )
308 {
309
310         struct client_connection *p, *x;
311
312         for ( p=connections; p; ) {
313                 cli_shutdown( p->cli );
314                 x = p;
315                 p = p->next;
316
317                 SAFE_FREE( x );
318         }
319
320         connections = NULL;
321         return;
322 }
323
324 /****************************************************************************
325 ****************************************************************************/
326
327 void cli_cm_display(void)
328 {
329         struct client_connection *p;
330         int i;
331
332         for ( p=connections,i=0; p; p=p->next,i++ ) {
333                 d_printf("%d:\tserver=%s, share=%s\n", 
334                         i, p->cli->desthost, p->cli->share );
335         }
336 }
337
338 /****************************************************************************
339 ****************************************************************************/
340
341 void cli_cm_set_credentials( struct user_auth_info *user )
342 {
343         pstrcpy( username, user->username );
344         
345         if ( user->got_pass ) {
346                 pstrcpy( password, user->password );
347                 got_pass = True;
348         }
349         
350         use_kerberos = user->use_kerberos;      
351         signing_state = user->signing_state;
352 }
353
354 /****************************************************************************
355 ****************************************************************************/
356
357 void cli_cm_set_port( int port_number )
358 {
359         port = port_number;
360 }
361
362 /****************************************************************************
363 ****************************************************************************/
364
365 void cli_cm_set_dest_name_type( int type )
366 {
367         name_type = type;
368 }
369
370 /****************************************************************************
371 ****************************************************************************/
372
373 void cli_cm_set_dest_ss(struct sockaddr_storage *pss)
374 {
375         dest_ss = *pss;
376         have_ip = true;
377 }
378
379 /**********************************************************************
380  split a dfs path into the server, share name, and extrapath components
381 **********************************************************************/
382
383 static void split_dfs_path( const char *nodepath, fstring server, fstring share, pstring extrapath )
384 {
385         char *p, *q;
386         pstring path;
387
388         pstrcpy( path, nodepath );
389
390         if ( path[0] != '\\' ) {
391                 return;
392         }
393
394         p = strchr_m( path + 1, '\\' );
395         if ( !p ) {
396                 return;
397         }
398
399         *p = '\0';
400         p++;
401
402         /* Look for any extra/deep path */
403         q = strchr_m(p, '\\');
404         if (q != NULL) {
405                 *q = '\0';
406                 q++;
407                 pstrcpy( extrapath, q );
408         } else {
409                 pstrcpy( extrapath, '\0' );
410         }
411         
412         fstrcpy( share, p );
413         fstrcpy( server, &path[1] );
414 }
415
416 /****************************************************************************
417  Return the original path truncated at the directory component before
418  the first wildcard character. Trust the caller to provide a NULL 
419  terminated string
420 ****************************************************************************/
421
422 static void clean_path(const char *path, pstring path_out)
423 {
424         size_t len;
425         char *p1, *p2, *p;
426                 
427         /* No absolute paths. */
428         while (IS_DIRECTORY_SEP(*path)) {
429                 path++;
430         }
431
432         pstrcpy(path_out, path);
433
434         p1 = strchr_m(path_out, '*');
435         p2 = strchr_m(path_out, '?');
436
437         if (p1 || p2) {
438                 if (p1 && p2) {
439                         p = MIN(p1,p2);
440                 } else if (!p1) {
441                         p = p2;
442                 } else {
443                         p = p1;
444                 }
445                 *p = '\0';
446
447                 /* Now go back to the start of this component. */
448                 p1 = strrchr_m(path_out, '/');
449                 p2 = strrchr_m(path_out, '\\');
450                 p = MAX(p1,p2);
451                 if (p) {
452                         *p = '\0';
453                 }
454         }
455
456         /* Strip any trailing separator */
457
458         len = strlen(path_out);
459         if ( (len > 0) && IS_DIRECTORY_SEP(path_out[len-1])) {
460                 path_out[len-1] = '\0';
461         }
462 }
463
464 /****************************************************************************
465 ****************************************************************************/
466
467 static void cli_dfs_make_full_path( struct cli_state *cli,
468                                         const char *dir,
469                                         pstring path_out)
470 {
471         /* Ensure the extrapath doesn't start with a separator. */
472         while (IS_DIRECTORY_SEP(*dir)) {
473                 dir++;
474         }
475
476         pstr_sprintf( path_out, "\\%s\\%s\\%s", cli->desthost, cli->share, dir);
477 }
478
479 /********************************************************************
480  check for dfs referral
481 ********************************************************************/
482
483 static bool cli_dfs_check_error( struct cli_state *cli, NTSTATUS status )
484 {
485         uint32 flgs2 = SVAL(cli->inbuf,smb_flg2);
486
487         /* only deal with DS when we negotiated NT_STATUS codes and UNICODE */
488
489         if ( !( (flgs2&FLAGS2_32_BIT_ERROR_CODES) && (flgs2&FLAGS2_UNICODE_STRINGS) ) )
490                 return False;
491
492         if ( NT_STATUS_EQUAL( status, NT_STATUS(IVAL(cli->inbuf,smb_rcls)) ) )
493                 return True;
494
495         return False;
496 }
497
498 /********************************************************************
499  get the dfs referral link
500 ********************************************************************/
501
502 bool cli_dfs_get_referral( struct cli_state *cli,
503                         const char *path, 
504                         CLIENT_DFS_REFERRAL**refs,
505                         size_t *num_refs,
506                         uint16 *consumed)
507 {
508         unsigned int data_len = 0;
509         unsigned int param_len = 0;
510         uint16 setup = TRANSACT2_GET_DFS_REFERRAL;
511         char param[sizeof(pstring)+2];
512         pstring data;
513         char *rparam=NULL, *rdata=NULL;
514         char *p;
515         size_t pathlen = 2*(strlen(path)+1);
516         uint16 num_referrals;
517         CLIENT_DFS_REFERRAL *referrals = NULL;
518         
519         memset(param, 0, sizeof(param));
520         SSVAL(param, 0, 0x03);  /* max referral level */
521         p = &param[2];
522
523         p += clistr_push(cli, p, path, MIN(pathlen, sizeof(param)-2), STR_TERMINATE);
524         param_len = PTR_DIFF(p, param);
525
526         if (!cli_send_trans(cli, SMBtrans2,
527                 NULL,                        /* name */
528                 -1, 0,                          /* fid, flags */
529                 &setup, 1, 0,                   /* setup, length, max */
530                 param, param_len, 2,            /* param, length, max */
531                 (char *)&data,  data_len, cli->max_xmit /* data, length, max */
532                 )) {
533                         return False;
534         }
535
536         if (!cli_receive_trans(cli, SMBtrans2,
537                 &rparam, &param_len,
538                 &rdata, &data_len)) {
539                         return False;
540         }
541         
542         *consumed     = SVAL( rdata, 0 );
543         num_referrals = SVAL( rdata, 2 );
544         
545         if ( num_referrals != 0 ) {
546                 uint16 ref_version;
547                 uint16 ref_size;
548                 int i;
549                 uint16 node_offset;
550
551                 referrals = SMB_XMALLOC_ARRAY( CLIENT_DFS_REFERRAL, num_referrals );
552
553                 /* start at the referrals array */
554         
555                 p = rdata+8;
556                 for ( i=0; i<num_referrals; i++ ) {
557                         ref_version = SVAL( p, 0 );
558                         ref_size    = SVAL( p, 2 );
559                         node_offset = SVAL( p, 16 );
560                         
561                         if ( ref_version != 3 ) {
562                                 p += ref_size;
563                                 continue;
564                         }
565                         
566                         referrals[i].proximity = SVAL( p, 8 );
567                         referrals[i].ttl       = SVAL( p, 10 );
568
569                         clistr_pull( cli, referrals[i].dfspath, p+node_offset, 
570                                 sizeof(referrals[i].dfspath), -1, STR_TERMINATE|STR_UNICODE );
571
572                         p += ref_size;
573                 }
574         }
575         
576         *num_refs = num_referrals;
577         *refs = referrals;
578
579         SAFE_FREE(rdata);
580         SAFE_FREE(rparam);
581
582         return True;
583 }
584
585
586 /********************************************************************
587 ********************************************************************/
588
589 bool cli_resolve_path( const char *mountpt,
590                         struct cli_state *rootcli,
591                         const char *path,
592                         struct cli_state **targetcli,
593                         pstring targetpath)
594 {
595         CLIENT_DFS_REFERRAL *refs = NULL;
596         size_t num_refs;
597         uint16 consumed;
598         struct cli_state *cli_ipc;
599         pstring dfs_path, cleanpath, extrapath;
600         int pathlen;
601         fstring server, share;
602         struct cli_state *newcli;
603         pstring newpath;
604         pstring newmount;
605         char *ppath, *temppath = NULL;
606         
607         SMB_STRUCT_STAT sbuf;
608         uint32 attributes;
609         
610         if ( !rootcli || !path || !targetcli ) {
611                 return False;
612         }
613                 
614         /* Don't do anything if this is not a DFS root. */
615
616         if ( !rootcli->dfsroot) {
617                 *targetcli = rootcli;
618                 pstrcpy( targetpath, path );
619                 return True;
620         }
621
622         *targetcli = NULL;
623
624         /* Send a trans2_query_path_info to check for a referral. */
625
626         clean_path(path, cleanpath);
627         cli_dfs_make_full_path(rootcli, cleanpath, dfs_path );
628
629         if (cli_qpathinfo_basic( rootcli, dfs_path, &sbuf, &attributes ) ) {
630                 /* This is an ordinary path, just return it. */
631                 *targetcli = rootcli;
632                 pstrcpy( targetpath, path );
633                 goto done;
634         }
635
636         /* Special case where client asked for a path that does not exist */
637
638         if ( cli_dfs_check_error(rootcli, NT_STATUS_OBJECT_NAME_NOT_FOUND) ) {
639                 *targetcli = rootcli;
640                 pstrcpy( targetpath, path );
641                 goto done;
642         }
643
644         /* We got an error, check for DFS referral. */
645
646         if ( !cli_dfs_check_error(rootcli, NT_STATUS_PATH_NOT_COVERED))  {
647                 return False;
648         }
649
650         /* Check for the referral. */
651
652         if ( !(cli_ipc = cli_cm_open( rootcli->desthost, "IPC$", False )) ) {
653                 return False;
654         }
655         
656         if ( !cli_dfs_get_referral(cli_ipc, dfs_path, &refs, &num_refs, &consumed) 
657                         || !num_refs ) {
658                 return False;
659         }
660         
661         /* Just store the first referral for now. */
662
663         split_dfs_path( refs[0].dfspath, server, share, extrapath );
664         SAFE_FREE(refs);
665
666         /* Make sure to recreate the original string including any wildcards. */
667         
668         cli_dfs_make_full_path( rootcli, path, dfs_path);
669         pathlen = strlen( dfs_path )*2;
670         consumed = MIN(pathlen, consumed );
671         pstrcpy( targetpath, &dfs_path[consumed/2] );
672         dfs_path[consumed/2] = '\0';
673
674         /*
675          * targetpath is now the unconsumed part of the path.
676          * dfs_path is now the consumed part of the path (in \server\share\path format).
677          */
678
679         /* Open the connection to the target server & share */
680         
681         if ( (*targetcli = cli_cm_open(server, share, False)) == NULL ) {
682                 d_printf("Unable to follow dfs referral [\\%s\\%s]\n",
683                         server, share );
684                 return False;
685         }
686         
687         if (strlen(extrapath) > 0) {
688                 string_append(&temppath, extrapath);
689                 string_append(&temppath, targetpath);
690                 pstrcpy( targetpath, temppath );
691         }
692         
693         /* parse out the consumed mount path */
694         /* trim off the \server\share\ */
695
696         ppath = dfs_path;
697
698         if (*ppath != '\\') {
699                 d_printf("cli_resolve_path: dfs_path (%s) not in correct format.\n",
700                         dfs_path );
701                 return False;
702         }
703
704         ppath++; /* Now pointing at start of server name. */
705         
706         if ((ppath = strchr_m( dfs_path, '\\' )) == NULL) {
707                 return False;
708         }
709
710         ppath++; /* Now pointing at start of share name. */
711
712         if ((ppath = strchr_m( ppath+1, '\\' )) == NULL) {
713                 return False;
714         }
715
716         ppath++; /* Now pointing at path component. */
717
718         pstr_sprintf( newmount, "%s\\%s", mountpt, ppath );
719
720         cli_cm_set_mntpoint( *targetcli, newmount );
721
722         /* Check for another dfs referral, note that we are not 
723            checking for loops here. */
724
725         if ( !strequal( targetpath, "\\" ) &&  !strequal( targetpath, "/")) {
726                 if ( cli_resolve_path( newmount, *targetcli, targetpath, &newcli, newpath ) ) {
727                         /*
728                          * When cli_resolve_path returns true here it's always
729                          * returning the complete path in newpath, so we're done
730                          * here.
731                          */
732                         *targetcli = newcli;
733                         pstrcpy( targetpath, newpath );
734                         return True;
735                 }
736         }
737
738   done:
739
740         /* If returning True ensure we return a dfs root full path. */
741         if ( (*targetcli)->dfsroot ) {
742                 pstrcpy(dfs_path, targetpath );
743                 cli_dfs_make_full_path( *targetcli, dfs_path, targetpath); 
744         }
745
746         return True;
747 }
748
749 /********************************************************************
750 ********************************************************************/
751
752 bool cli_check_msdfs_proxy( struct cli_state *cli, const char *sharename,
753                             fstring newserver, fstring newshare )
754 {
755         CLIENT_DFS_REFERRAL *refs = NULL;
756         size_t num_refs;
757         uint16 consumed;
758         pstring fullpath;
759         bool res;
760         uint16 cnum;
761         pstring newextrapath;
762         
763         if ( !cli || !sharename )
764                 return False;
765
766         cnum = cli->cnum;
767
768         /* special case.  never check for a referral on the IPC$ share */
769
770         if ( strequal( sharename, "IPC$" ) ) {
771                 return False;
772         }
773                 
774         /* send a trans2_query_path_info to check for a referral */
775         
776         pstr_sprintf( fullpath, "\\%s\\%s", cli->desthost, sharename );
777
778         /* check for the referral */
779
780         if (!cli_send_tconX(cli, "IPC$", "IPC", NULL, 0)) {
781                 return False;
782         }
783
784         res = cli_dfs_get_referral(cli, fullpath, &refs, &num_refs, &consumed);
785
786         if (!cli_tdis(cli)) {
787                 SAFE_FREE( refs );
788                 return False;
789         }
790
791         cli->cnum = cnum;
792
793         if (!res || !num_refs ) {
794                 SAFE_FREE( refs );
795                 return False;
796         }
797         
798         split_dfs_path( refs[0].dfspath, newserver, newshare, newextrapath );
799
800         /* check that this is not a self-referral */
801
802         if ( strequal( cli->desthost, newserver ) && strequal( sharename, newshare ) ) {
803                 SAFE_FREE( refs );
804                 return False;
805         }
806         
807         SAFE_FREE( refs );
808         
809         return True;
810 }