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