s3:libsmb: pass 'dest_ss' from cli_cm_connect() via do_connect() to cli_connect_nb()
[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-2009
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 #include "libsmb/libsmb.h"
24 #include "libsmb/clirap.h"
25 #include "msdfs.h"
26 #include "trans2.h"
27 #include "libsmb/nmblib.h"
28 #include "../libcli/smb/smbXcli_base.h"
29 #include "auth/credentials/credentials.h"
30
31 /********************************************************************
32  Important point.
33
34  DFS paths are *always* of the form \server\share\<pathname> (the \ characters
35  are not C escaped here).
36
37  - but if we're using POSIX paths then <pathname> may contain
38    '/' separators, not '\\' separators. So cope with '\\' or '/'
39    as a separator when looking at the pathname part.... JRA.
40 ********************************************************************/
41
42 /********************************************************************
43  Ensure a connection is encrypted.
44 ********************************************************************/
45
46 NTSTATUS cli_cm_force_encryption_creds(struct cli_state *c,
47                                        struct cli_credentials *creds,
48                                        const char *sharename)
49 {
50         uint16_t major, minor;
51         uint32_t caplow, caphigh;
52         NTSTATUS status;
53
54         if (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) {
55                 status = smb2cli_session_encryption_on(c->smb2.session);
56                 if (NT_STATUS_EQUAL(status,NT_STATUS_NOT_SUPPORTED)) {
57                         d_printf("Encryption required and "
58                                 "server doesn't support "
59                                 "SMB3 encryption - failing connect\n");
60                 } else if (!NT_STATUS_IS_OK(status)) {
61                         d_printf("Encryption required and "
62                                 "setup failed with error %s.\n",
63                                 nt_errstr(status));
64                 }
65                 return status;
66         }
67
68         if (!SERVER_HAS_UNIX_CIFS(c)) {
69                 d_printf("Encryption required and "
70                         "server that doesn't support "
71                         "UNIX extensions - failing connect\n");
72                 return NT_STATUS_NOT_SUPPORTED;
73         }
74
75         status = cli_unix_extensions_version(c, &major, &minor, &caplow,
76                                              &caphigh);
77         if (!NT_STATUS_IS_OK(status)) {
78                 d_printf("Encryption required and "
79                         "can't get UNIX CIFS extensions "
80                         "version from server.\n");
81                 return NT_STATUS_UNKNOWN_REVISION;
82         }
83
84         if (!(caplow & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)) {
85                 d_printf("Encryption required and "
86                         "share %s doesn't support "
87                         "encryption.\n", sharename);
88                 return NT_STATUS_UNSUPPORTED_COMPRESSION;
89         }
90
91         status = cli_smb1_setup_encryption(c, creds);
92         if (!NT_STATUS_IS_OK(status)) {
93                 d_printf("Encryption required and "
94                         "setup failed with error %s.\n",
95                         nt_errstr(status));
96                 return status;
97         }
98
99         return NT_STATUS_OK;
100 }
101
102 NTSTATUS cli_cm_force_encryption(struct cli_state *c,
103                         const char *username,
104                         const char *password,
105                         const char *domain,
106                         const char *sharename)
107 {
108         struct cli_credentials *creds = NULL;
109         NTSTATUS status;
110
111         creds = cli_session_creds_init(c,
112                                        username,
113                                        domain,
114                                        NULL, /* default realm */
115                                        password,
116                                        c->use_kerberos,
117                                        c->fallback_after_kerberos,
118                                        c->use_ccache,
119                                        c->pw_nt_hash);
120         if (creds == NULL) {
121                 return NT_STATUS_NO_MEMORY;
122         }
123
124         status = cli_cm_force_encryption_creds(c, creds, sharename);
125         /* gensec currently references the creds so we can't free them here */
126         talloc_unlink(c, creds);
127         return status;
128 }
129
130 /********************************************************************
131  Return a connection to a server.
132 ********************************************************************/
133
134 static NTSTATUS do_connect(TALLOC_CTX *ctx,
135                                         const char *server,
136                                         const struct sockaddr_storage *dest_ss,
137                                         const char *share,
138                                         const struct user_auth_info *auth_info,
139                                         bool show_sessetup,
140                                         bool force_encrypt,
141                                         int max_protocol,
142                                         int port,
143                                         int name_type,
144                                         struct cli_state **pcli)
145 {
146         struct cli_state *c = NULL;
147         char *servicename;
148         char *sharename;
149         char *newserver, *newshare;
150         NTSTATUS status;
151         int flags = 0;
152         enum protocol_types protocol = PROTOCOL_NONE;
153         int signing_state = get_cmdline_auth_info_signing_state(auth_info);
154         struct cli_credentials *creds = NULL;
155
156         if (force_encrypt) {
157                 signing_state = SMB_SIGNING_REQUIRED;
158         }
159
160         /* make a copy so we don't modify the global string 'service' */
161         servicename = talloc_strdup(ctx,share);
162         if (!servicename) {
163                 return NT_STATUS_NO_MEMORY;
164         }
165         sharename = servicename;
166         if (*sharename == '\\') {
167                 sharename += 2;
168                 if (server == NULL) {
169                         server = sharename;
170                 }
171                 sharename = strchr_m(sharename,'\\');
172                 if (!sharename) {
173                         return NT_STATUS_NO_MEMORY;
174                 }
175                 *sharename = 0;
176                 sharename++;
177         }
178         if (server == NULL) {
179                 return NT_STATUS_INVALID_PARAMETER;
180         }
181
182         if (get_cmdline_auth_info_use_kerberos(auth_info)) {
183                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
184         }
185         if (get_cmdline_auth_info_fallback_after_kerberos(auth_info)) {
186                 flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
187         }
188         if (get_cmdline_auth_info_use_ccache(auth_info)) {
189                 flags |= CLI_FULL_CONNECTION_USE_CCACHE;
190         }
191         if (get_cmdline_auth_info_use_pw_nt_hash(auth_info)) {
192                 flags |= CLI_FULL_CONNECTION_USE_NT_HASH;
193         }
194
195         status = cli_connect_nb(
196                 server, dest_ss, port, name_type, NULL,
197                 signing_state,
198                 flags, &c);
199
200         if (!NT_STATUS_IS_OK(status)) {
201                 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_SUPPORTED)) {
202                         DBG_ERR("NetBIOS support disabled, unable to connect");
203                 }
204
205                 DBG_WARNING("Connection to %s failed (Error %s)\n",
206                             server,
207                             nt_errstr(status));
208                 return status;
209         }
210
211         if (max_protocol == 0) {
212                 max_protocol = PROTOCOL_LATEST;
213         }
214         DEBUG(4,(" session request ok\n"));
215
216         status = smbXcli_negprot(c->conn, c->timeout,
217                                  lp_client_min_protocol(),
218                                  max_protocol);
219
220         if (!NT_STATUS_IS_OK(status)) {
221                 d_printf("protocol negotiation failed: %s\n",
222                          nt_errstr(status));
223                 cli_shutdown(c);
224                 return status;
225         }
226         protocol = smbXcli_conn_protocol(c->conn);
227         DEBUG(4,(" negotiated dialect[%s] against server[%s]\n",
228                  smb_protocol_types_string(protocol),
229                  smbXcli_conn_remote_name(c->conn)));
230
231         if (protocol >= PROTOCOL_SMB2_02) {
232                 /* Ensure we ask for some initial credits. */
233                 smb2cli_conn_set_max_credits(c->conn, DEFAULT_SMB2_MAX_CREDITS);
234         }
235
236         creds = get_cmdline_auth_info_creds(auth_info);
237
238         status = cli_session_setup_creds(c, creds);
239         if (!NT_STATUS_IS_OK(status)) {
240                 /* If a password was not supplied then
241                  * try again with a null username. */
242                 if (force_encrypt || smbXcli_conn_signing_mandatory(c->conn) ||
243                         cli_credentials_authentication_requested(creds) ||
244                         cli_credentials_is_anonymous(creds) ||
245                         !NT_STATUS_IS_OK(status = cli_session_setup_anon(c)))
246                 {
247                         d_printf("session setup failed: %s\n",
248                                  nt_errstr(status));
249                         if (NT_STATUS_EQUAL(status,
250                                             NT_STATUS_MORE_PROCESSING_REQUIRED))
251                                 d_printf("did you forget to run kinit?\n");
252                         cli_shutdown(c);
253                         return status;
254                 }
255                 d_printf("Anonymous login successful\n");
256         }
257
258         if (!NT_STATUS_IS_OK(status)) {
259                 DEBUG(10,("cli_init_creds() failed: %s\n", nt_errstr(status)));
260                 cli_shutdown(c);
261                 return status;
262         }
263
264         if ( show_sessetup ) {
265                 if (*c->server_domain) {
266                         DEBUG(0,("Domain=[%s] OS=[%s] Server=[%s]\n",
267                                 c->server_domain,c->server_os,c->server_type));
268                 } else if (*c->server_os || *c->server_type) {
269                         DEBUG(0,("OS=[%s] Server=[%s]\n",
270                                  c->server_os,c->server_type));
271                 }
272         }
273         DEBUG(4,(" session setup ok\n"));
274
275         /* here's the fun part....to support 'msdfs proxy' shares
276            (on Samba or windows) we have to issues a TRANS_GET_DFS_REFERRAL
277            here before trying to connect to the original share.
278            cli_check_msdfs_proxy() will fail if it is a normal share. */
279
280         if (smbXcli_conn_dfs_supported(c->conn) &&
281                         cli_check_msdfs_proxy(ctx, c, sharename,
282                                 &newserver, &newshare,
283                                 force_encrypt, creds)) {
284                 cli_shutdown(c);
285                 return do_connect(ctx, newserver, NULL,
286                                 newshare, auth_info, false,
287                                 force_encrypt, max_protocol,
288                                 port, name_type, pcli);
289         }
290
291         /* must be a normal share */
292
293         status = cli_tree_connect_creds(c, sharename, "?????", creds);
294         if (!NT_STATUS_IS_OK(status)) {
295                 d_printf("tree connect failed: %s\n", nt_errstr(status));
296                 cli_shutdown(c);
297                 return status;
298         }
299
300         if (force_encrypt) {
301                 status = cli_cm_force_encryption_creds(c,
302                                                        creds,
303                                                        sharename);
304                 if (!NT_STATUS_IS_OK(status)) {
305                         cli_shutdown(c);
306                         return status;
307                 }
308         }
309
310         DEBUG(4,(" tconx ok\n"));
311         *pcli = c;
312         return NT_STATUS_OK;
313 }
314
315 /****************************************************************************
316 ****************************************************************************/
317
318 static void cli_set_mntpoint(struct cli_state *cli, const char *mnt)
319 {
320         TALLOC_CTX *frame = talloc_stackframe();
321         char *name = clean_name(frame, mnt);
322         if (!name) {
323                 TALLOC_FREE(frame);
324                 return;
325         }
326         TALLOC_FREE(cli->dfs_mountpoint);
327         cli->dfs_mountpoint = talloc_strdup(cli, name);
328         TALLOC_FREE(frame);
329 }
330
331 /********************************************************************
332  Add a new connection to the list.
333  referring_cli == NULL means a new initial connection.
334 ********************************************************************/
335
336 static NTSTATUS cli_cm_connect(TALLOC_CTX *ctx,
337                                struct cli_state *referring_cli,
338                                const char *server,
339                                const struct sockaddr_storage *dest_ss,
340                                const char *share,
341                                const struct user_auth_info *auth_info,
342                                bool force_encrypt,
343                                int max_protocol,
344                                int port,
345                                int name_type,
346                                struct cli_state **pcli)
347 {
348         struct cli_state *cli;
349         NTSTATUS status;
350
351         status = do_connect(ctx, server, dest_ss, share,
352                                 auth_info,
353                                 show_hdr, force_encrypt, max_protocol,
354                                 port, name_type, &cli);
355
356         if (!NT_STATUS_IS_OK(status)) {
357                 return status;
358         }
359
360         /* Enter into the list. */
361         if (referring_cli) {
362                 DLIST_ADD_END(referring_cli, cli);
363         }
364
365         if (referring_cli && referring_cli->requested_posix_capabilities) {
366                 uint16_t major, minor;
367                 uint32_t caplow, caphigh;
368                 status = cli_unix_extensions_version(cli, &major, &minor,
369                                                      &caplow, &caphigh);
370                 if (NT_STATUS_IS_OK(status)) {
371                         cli_set_unix_extensions_capabilities(cli,
372                                         major, minor,
373                                         caplow, caphigh);
374                 }
375         }
376
377         *pcli = cli;
378         return NT_STATUS_OK;
379 }
380
381 /********************************************************************
382  Return a connection to a server on a particular share.
383 ********************************************************************/
384
385 static struct cli_state *cli_cm_find(struct cli_state *cli,
386                                 const char *server,
387                                 const char *share)
388 {
389         struct cli_state *p;
390
391         if (cli == NULL) {
392                 return NULL;
393         }
394
395         /* Search to the start of the list. */
396         for (p = cli; p; p = DLIST_PREV(p)) {
397                 const char *remote_name =
398                         smbXcli_conn_remote_name(p->conn);
399
400                 if (strequal(server, remote_name) &&
401                                 strequal(share,p->share)) {
402                         return p;
403                 }
404         }
405
406         /* Search to the end of the list. */
407         for (p = cli->next; p; p = p->next) {
408                 const char *remote_name =
409                         smbXcli_conn_remote_name(p->conn);
410
411                 if (strequal(server, remote_name) &&
412                                 strequal(share,p->share)) {
413                         return p;
414                 }
415         }
416
417         return NULL;
418 }
419
420 /****************************************************************************
421  Open a client connection to a \\server\share.
422 ****************************************************************************/
423
424 NTSTATUS cli_cm_open(TALLOC_CTX *ctx,
425                                 struct cli_state *referring_cli,
426                                 const char *server,
427                                 const char *share,
428                                 const struct user_auth_info *auth_info,
429                                 bool force_encrypt,
430                                 int max_protocol,
431                                 int port,
432                                 int name_type,
433                                 struct cli_state **pcli)
434 {
435         /* Try to reuse an existing connection in this list. */
436         struct cli_state *c = cli_cm_find(referring_cli, server, share);
437         NTSTATUS status;
438
439         if (c) {
440                 *pcli = c;
441                 return NT_STATUS_OK;
442         }
443
444         if (auth_info == NULL) {
445                 /* Can't do a new connection
446                  * without auth info. */
447                 d_printf("cli_cm_open() Unable to open connection [\\%s\\%s] "
448                         "without auth info\n",
449                         server, share );
450                 return NT_STATUS_INVALID_PARAMETER;
451         }
452
453         status = cli_cm_connect(ctx,
454                                 referring_cli,
455                                 server,
456                                 NULL,
457                                 share,
458                                 auth_info,
459                                 force_encrypt,
460                                 max_protocol,
461                                 port,
462                                 name_type,
463                                 &c);
464         if (!NT_STATUS_IS_OK(status)) {
465                 return status;
466         }
467         *pcli = c;
468         return NT_STATUS_OK;
469 }
470
471 /****************************************************************************
472 ****************************************************************************/
473
474 void cli_cm_display(struct cli_state *cli)
475 {
476         int i;
477
478         for (i=0; cli; cli = cli->next,i++ ) {
479                 d_printf("%d:\tserver=%s, share=%s\n",
480                         i, smbXcli_conn_remote_name(cli->conn), cli->share);
481         }
482 }
483
484 /****************************************************************************
485 ****************************************************************************/
486
487 /****************************************************************************
488 ****************************************************************************/
489
490 #if 0
491 void cli_cm_set_credentials(struct user_auth_info *auth_info)
492 {
493         SAFE_FREE(cm_creds.username);
494         cm_creds.username = SMB_STRDUP(get_cmdline_auth_info_username(
495                                                auth_info));
496
497         if (get_cmdline_auth_info_got_pass(auth_info)) {
498                 cm_set_password(get_cmdline_auth_info_password(auth_info));
499         }
500
501         cm_creds.use_kerberos = get_cmdline_auth_info_use_kerberos(auth_info);
502         cm_creds.fallback_after_kerberos = false;
503         cm_creds.signing_state = get_cmdline_auth_info_signing_state(auth_info);
504 }
505 #endif
506
507 /**********************************************************************
508  split a dfs path into the server, share name, and extrapath components
509 **********************************************************************/
510
511 static bool split_dfs_path(TALLOC_CTX *ctx,
512                                 const char *nodepath,
513                                 char **pp_server,
514                                 char **pp_share,
515                                 char **pp_extrapath)
516 {
517         char *p, *q;
518         char *path;
519
520         *pp_server = NULL;
521         *pp_share = NULL;
522         *pp_extrapath = NULL;
523
524         path = talloc_strdup(ctx, nodepath);
525         if (!path) {
526                 goto fail;
527         }
528
529         if ( path[0] != '\\' ) {
530                 goto fail;
531         }
532
533         p = strchr_m( path + 1, '\\' );
534         if ( !p ) {
535                 goto fail;
536         }
537
538         *p = '\0';
539         p++;
540
541         /* Look for any extra/deep path */
542         q = strchr_m(p, '\\');
543         if (q != NULL) {
544                 *q = '\0';
545                 q++;
546                 *pp_extrapath = talloc_strdup(ctx, q);
547         } else {
548                 *pp_extrapath = talloc_strdup(ctx, "");
549         }
550         if (*pp_extrapath == NULL) {
551                 goto fail;
552         }
553
554         *pp_share = talloc_strdup(ctx, p);
555         if (*pp_share == NULL) {
556                 goto fail;
557         }
558
559         *pp_server = talloc_strdup(ctx, &path[1]);
560         if (*pp_server == NULL) {
561                 goto fail;
562         }
563
564         TALLOC_FREE(path);
565         return true;
566
567 fail:
568         TALLOC_FREE(*pp_share);
569         TALLOC_FREE(*pp_extrapath);
570         TALLOC_FREE(path);
571         return false;
572 }
573
574 /****************************************************************************
575  Return the original path truncated at the directory component before
576  the first wildcard character. Trust the caller to provide a NULL
577  terminated string
578 ****************************************************************************/
579
580 static char *clean_path(TALLOC_CTX *ctx, const char *path)
581 {
582         size_t len;
583         char *p1, *p2, *p;
584         char *path_out;
585
586         /* No absolute paths. */
587         while (IS_DIRECTORY_SEP(*path)) {
588                 path++;
589         }
590
591         path_out = talloc_strdup(ctx, path);
592         if (!path_out) {
593                 return NULL;
594         }
595
596         p1 = strchr_m(path_out, '*');
597         p2 = strchr_m(path_out, '?');
598
599         if (p1 || p2) {
600                 if (p1 && p2) {
601                         p = MIN(p1,p2);
602                 } else if (!p1) {
603                         p = p2;
604                 } else {
605                         p = p1;
606                 }
607                 *p = '\0';
608
609                 /* Now go back to the start of this component. */
610                 p1 = strrchr_m(path_out, '/');
611                 p2 = strrchr_m(path_out, '\\');
612                 p = MAX(p1,p2);
613                 if (p) {
614                         *p = '\0';
615                 }
616         }
617
618         /* Strip any trailing separator */
619
620         len = strlen(path_out);
621         if ( (len > 0) && IS_DIRECTORY_SEP(path_out[len-1])) {
622                 path_out[len-1] = '\0';
623         }
624
625         return path_out;
626 }
627
628 /****************************************************************************
629 ****************************************************************************/
630
631 static char *cli_dfs_make_full_path(TALLOC_CTX *ctx,
632                                         struct cli_state *cli,
633                                         const char *dir)
634 {
635         char path_sep = '\\';
636
637         /* Ensure the extrapath doesn't start with a separator. */
638         while (IS_DIRECTORY_SEP(*dir)) {
639                 dir++;
640         }
641
642         if (cli->requested_posix_capabilities & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
643                 path_sep = '/';
644         }
645         return talloc_asprintf(ctx, "%c%s%c%s%c%s",
646                         path_sep,
647                         smbXcli_conn_remote_name(cli->conn),
648                         path_sep,
649                         cli->share,
650                         path_sep,
651                         dir);
652 }
653
654 /********************************************************************
655  check for dfs referral
656 ********************************************************************/
657
658 static bool cli_dfs_check_error(struct cli_state *cli, NTSTATUS expected,
659                                 NTSTATUS status)
660 {
661         /* only deal with DS when we negotiated NT_STATUS codes and UNICODE */
662
663         if (!(smbXcli_conn_use_unicode(cli->conn))) {
664                 return false;
665         }
666         if (!(smb1cli_conn_capabilities(cli->conn) & CAP_STATUS32)) {
667                 return false;
668         }
669         if (NT_STATUS_EQUAL(status, expected)) {
670                 return true;
671         }
672         return false;
673 }
674
675 /********************************************************************
676  Get the dfs referral link.
677 ********************************************************************/
678
679 NTSTATUS cli_dfs_get_referral_ex(TALLOC_CTX *ctx,
680                         struct cli_state *cli,
681                         const char *path,
682                         uint16_t max_referral_level,
683                         struct client_dfs_referral **refs,
684                         size_t *num_refs,
685                         size_t *consumed)
686 {
687         unsigned int param_len = 0;
688         uint16_t recv_flags2;
689         uint8_t *param = NULL;
690         uint8_t *rdata = NULL;
691         char *p;
692         char *endp;
693         smb_ucs2_t *path_ucs;
694         char *consumed_path = NULL;
695         uint16_t consumed_ucs;
696         uint16_t num_referrals;
697         struct client_dfs_referral *referrals = NULL;
698         NTSTATUS status;
699         TALLOC_CTX *frame = talloc_stackframe();
700
701         *num_refs = 0;
702         *refs = NULL;
703
704         param = talloc_array(talloc_tos(), uint8_t, 2);
705         if (!param) {
706                 status = NT_STATUS_NO_MEMORY;
707                 goto out;
708         }
709         SSVAL(param, 0, max_referral_level);
710
711         param = trans2_bytes_push_str(param, smbXcli_conn_use_unicode(cli->conn),
712                                       path, strlen(path)+1,
713                                       NULL);
714         if (!param) {
715                 status = NT_STATUS_NO_MEMORY;
716                 goto out;
717         }
718         param_len = talloc_get_size(param);
719         path_ucs = (smb_ucs2_t *)&param[2];
720
721         if (smbXcli_conn_protocol(cli->conn) >= PROTOCOL_SMB2_02) {
722                 DATA_BLOB in_input_buffer;
723                 DATA_BLOB in_output_buffer = data_blob_null;
724                 DATA_BLOB out_input_buffer = data_blob_null;
725                 DATA_BLOB out_output_buffer = data_blob_null;
726
727                 in_input_buffer.data = param;
728                 in_input_buffer.length = param_len;
729
730                 status = smb2cli_ioctl(cli->conn,
731                                        cli->timeout,
732                                        cli->smb2.session,
733                                        cli->smb2.tcon,
734                                        UINT64_MAX, /* in_fid_persistent */
735                                        UINT64_MAX, /* in_fid_volatile */
736                                        FSCTL_DFS_GET_REFERRALS,
737                                        0, /* in_max_input_length */
738                                        &in_input_buffer,
739                                        CLI_BUFFER_SIZE, /* in_max_output_length */
740                                        &in_output_buffer,
741                                        SMB2_IOCTL_FLAG_IS_FSCTL,
742                                        talloc_tos(),
743                                        &out_input_buffer,
744                                        &out_output_buffer);
745                 if (!NT_STATUS_IS_OK(status)) {
746                         goto out;
747                 }
748
749                 if (out_output_buffer.length < 4) {
750                         status = NT_STATUS_INVALID_NETWORK_RESPONSE;
751                         goto out;
752                 }
753
754                 recv_flags2 = FLAGS2_UNICODE_STRINGS;
755                 rdata = out_output_buffer.data;
756                 endp = (char *)rdata + out_output_buffer.length;
757         } else {
758                 unsigned int data_len = 0;
759                 uint16_t setup[1];
760
761                 SSVAL(setup, 0, TRANSACT2_GET_DFS_REFERRAL);
762
763                 status = cli_trans(talloc_tos(), cli, SMBtrans2,
764                                    NULL, 0xffff, 0, 0,
765                                    setup, 1, 0,
766                                    param, param_len, 2,
767                                    NULL, 0, CLI_BUFFER_SIZE,
768                                    &recv_flags2,
769                                    NULL, 0, NULL, /* rsetup */
770                                    NULL, 0, NULL,
771                                    &rdata, 4, &data_len);
772                 if (!NT_STATUS_IS_OK(status)) {
773                         goto out;
774                 }
775
776                 endp = (char *)rdata + data_len;
777         }
778
779         consumed_ucs  = SVAL(rdata, 0);
780         num_referrals = SVAL(rdata, 2);
781
782         /* consumed_ucs is the number of bytes
783          * of the UCS2 path consumed not counting any
784          * terminating null. We need to convert
785          * back to unix charset and count again
786          * to get the number of bytes consumed from
787          * the incoming path. */
788
789         errno = 0;
790         if (pull_string_talloc(talloc_tos(),
791                         NULL,
792                         0,
793                         &consumed_path,
794                         path_ucs,
795                         consumed_ucs,
796                         STR_UNICODE) == 0) {
797                 if (errno != 0) {
798                         status = map_nt_error_from_unix(errno);
799                 } else {
800                         status = NT_STATUS_INVALID_NETWORK_RESPONSE;
801                 }
802                 goto out;
803         }
804         if (consumed_path == NULL) {
805                 status = map_nt_error_from_unix(errno);
806                 goto out;
807         }
808         *consumed = strlen(consumed_path);
809
810         if (num_referrals != 0) {
811                 uint16_t ref_version;
812                 uint16_t ref_size;
813                 int i;
814                 uint16_t node_offset;
815
816                 referrals = talloc_array(ctx, struct client_dfs_referral,
817                                          num_referrals);
818
819                 if (!referrals) {
820                         status = NT_STATUS_NO_MEMORY;
821                         goto out;
822                 }
823                 /* start at the referrals array */
824
825                 p = (char *)rdata+8;
826                 for (i=0; i<num_referrals && p < endp; i++) {
827                         if (p + 18 > endp) {
828                                 goto out;
829                         }
830                         ref_version = SVAL(p, 0);
831                         ref_size    = SVAL(p, 2);
832                         node_offset = SVAL(p, 16);
833
834                         if (ref_version != 3) {
835                                 p += ref_size;
836                                 continue;
837                         }
838
839                         referrals[i].proximity = SVAL(p, 8);
840                         referrals[i].ttl       = SVAL(p, 10);
841
842                         if (p + node_offset > endp) {
843                                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
844                                 goto out;
845                         }
846                         clistr_pull_talloc(referrals,
847                                            (const char *)rdata,
848                                            recv_flags2,
849                                            &referrals[i].dfspath,
850                                            p+node_offset,
851                                            PTR_DIFF(endp, p+node_offset),
852                                            STR_TERMINATE|STR_UNICODE);
853
854                         if (!referrals[i].dfspath) {
855                                 status = map_nt_error_from_unix(errno);
856                                 goto out;
857                         }
858                         p += ref_size;
859                 }
860                 if (i < num_referrals) {
861                         status = NT_STATUS_INVALID_NETWORK_RESPONSE;
862                         goto out;
863                 }
864         }
865
866         *num_refs = num_referrals;
867         *refs = referrals;
868
869   out:
870
871         TALLOC_FREE(frame);
872         return status;
873 }
874
875 NTSTATUS cli_dfs_get_referral(TALLOC_CTX *ctx,
876                         struct cli_state *cli,
877                         const char *path,
878                         struct client_dfs_referral **refs,
879                         size_t *num_refs,
880                         size_t *consumed)
881 {
882         return cli_dfs_get_referral_ex(ctx,
883                                 cli,
884                                 path,
885                                 3,
886                                 refs, /* Max referral level we want */
887                                 num_refs,
888                                 consumed);
889 }
890
891 /********************************************************************
892 ********************************************************************/
893 struct cli_dfs_path_split {
894         char *server;
895         char *share;
896         char *extrapath;
897 };
898
899 NTSTATUS cli_resolve_path(TALLOC_CTX *ctx,
900                           const char *mountpt,
901                           const struct user_auth_info *dfs_auth_info,
902                           struct cli_state *rootcli,
903                           const char *path,
904                           struct cli_state **targetcli,
905                           char **pp_targetpath)
906 {
907         struct client_dfs_referral *refs = NULL;
908         size_t num_refs = 0;
909         size_t consumed = 0;
910         struct cli_state *cli_ipc = NULL;
911         char *dfs_path = NULL;
912         char *cleanpath = NULL;
913         char *extrapath = NULL;
914         int pathlen;
915         struct cli_state *newcli = NULL;
916         struct cli_state *ccli = NULL;
917         int count = 0;
918         char *newpath = NULL;
919         char *newmount = NULL;
920         char *ppath = NULL;
921         SMB_STRUCT_STAT sbuf;
922         uint32_t attributes;
923         NTSTATUS status;
924         struct cli_credentials *dfs_creds = NULL;
925         bool force_encryption = true;
926         struct smbXcli_tcon *root_tcon = NULL;
927         struct smbXcli_tcon *target_tcon = NULL;
928         struct cli_dfs_path_split *dfs_refs = NULL;
929
930         if ( !rootcli || !path || !targetcli ) {
931                 return NT_STATUS_INVALID_PARAMETER;
932         }
933
934         /* Don't do anything if this is not a DFS root. */
935
936         if (smbXcli_conn_protocol(rootcli->conn) >= PROTOCOL_SMB2_02) {
937                 root_tcon = rootcli->smb2.tcon;
938                 force_encryption = smb2cli_tcon_is_encryption_on(root_tcon);
939         } else {
940                 root_tcon = rootcli->smb1.tcon;
941                 force_encryption = smb1cli_conn_encryption_on(rootcli->conn);
942         }
943
944         /*
945          * Avoid more than one leading directory separator
946          */
947         while (IS_DIRECTORY_SEP(path[0]) && IS_DIRECTORY_SEP(path[1])) {
948                 path++;
949         }
950
951         if (!smbXcli_tcon_is_dfs_share(root_tcon)) {
952                 *targetcli = rootcli;
953                 *pp_targetpath = talloc_strdup(ctx, path);
954                 if (!*pp_targetpath) {
955                         return NT_STATUS_NO_MEMORY;
956                 }
957                 return NT_STATUS_OK;
958         }
959
960         *targetcli = NULL;
961
962         /* Send a trans2_query_path_info to check for a referral. */
963
964         cleanpath = clean_path(ctx, path);
965         if (!cleanpath) {
966                 return NT_STATUS_NO_MEMORY;
967         }
968
969         dfs_path = cli_dfs_make_full_path(ctx, rootcli, cleanpath);
970         if (!dfs_path) {
971                 return NT_STATUS_NO_MEMORY;
972         }
973
974         status = cli_qpathinfo_basic( rootcli, dfs_path, &sbuf, &attributes);
975         if (NT_STATUS_IS_OK(status)) {
976                 /* This is an ordinary path, just return it. */
977                 *targetcli = rootcli;
978                 *pp_targetpath = talloc_strdup(ctx, path);
979                 if (!*pp_targetpath) {
980                         return NT_STATUS_NO_MEMORY;
981                 }
982                 goto done;
983         }
984
985         /* Special case where client asked for a path that does not exist */
986
987         if (cli_dfs_check_error(rootcli, NT_STATUS_OBJECT_NAME_NOT_FOUND,
988                                 status)) {
989                 *targetcli = rootcli;
990                 *pp_targetpath = talloc_strdup(ctx, path);
991                 if (!*pp_targetpath) {
992                         return NT_STATUS_NO_MEMORY;
993                 }
994                 goto done;
995         }
996
997         /* We got an error, check for DFS referral. */
998
999         if (!cli_dfs_check_error(rootcli, NT_STATUS_PATH_NOT_COVERED,
1000                                  status)) {
1001                 return status;
1002         }
1003
1004         /* Check for the referral. */
1005
1006         cli_ipc = cli_state_dup(ctx, rootcli);
1007         if (cli_ipc == NULL) {
1008                 return NT_STATUS_NO_MEMORY;
1009         }
1010
1011         dfs_creds = get_cmdline_auth_info_creds(auth_info);
1012
1013         status = cli_tree_connect_creds(cli_ipc, "IPC$", "IPC", dfs_creds);
1014         if (!NT_STATUS_IS_OK(status)) {
1015                 d_printf("tree connect failed: %s\n", nt_errstr(status));
1016                 cli_shutdown(cli_ipc);
1017                 return status;
1018         }
1019
1020         if (force_encrypt) {
1021                 status = cli_cm_force_encryption_creds(cli_ipc,
1022                                                        dfs_creds,
1023                                                        "IPC$");
1024                 if (!NT_STATUS_IS_OK(status)) {
1025                         cli_shutdown(cli_ipc);
1026                         return status;
1027                 }
1028         }
1029
1030         status = cli_dfs_get_referral(ctx, cli_ipc, dfs_path, &refs,
1031                                       &num_refs, &consumed);
1032         if (!NT_STATUS_IS_OK(status)) {
1033                 return status;
1034         }
1035
1036         if (!num_refs || !refs[0].dfspath) {
1037                 return NT_STATUS_NOT_FOUND;
1038         }
1039
1040         /*
1041          * Bug#10123 - DFS referal entries can be provided in a random order,
1042          * so check the connection cache for each item to avoid unnecessary
1043          * reconnections.
1044          */
1045         dfs_refs = talloc_array(ctx, struct cli_dfs_path_split, num_refs);
1046         if (dfs_refs == NULL) {
1047                 return NT_STATUS_NO_MEMORY;
1048         }
1049
1050         for (count = 0; count < num_refs; count++) {
1051                 if (!split_dfs_path(dfs_refs, refs[count].dfspath,
1052                                     &dfs_refs[count].server,
1053                                     &dfs_refs[count].share,
1054                                     &dfs_refs[count].extrapath)) {
1055                         TALLOC_FREE(dfs_refs);
1056                         return NT_STATUS_NOT_FOUND;
1057                 }
1058
1059                 ccli = cli_cm_find(rootcli, dfs_refs[count].server,
1060                                    dfs_refs[count].share);
1061                 if (ccli != NULL) {
1062                         extrapath = dfs_refs[count].extrapath;
1063                         *targetcli = ccli;
1064                         break;
1065                 }
1066         }
1067
1068         /*
1069          * If no cached connection was found, then connect to the first live
1070          * referral server in the list.
1071          */
1072         for (count = 0; (ccli == NULL) && (count < num_refs); count++) {
1073                 /* Connect to the target server & share */
1074                 status = cli_cm_connect(ctx, rootcli,
1075                                 dfs_refs[count].server,
1076                                 NULL,
1077                                 dfs_refs[count].share,
1078                                 dfs_auth_info,
1079                                 cli_state_is_encryption_on(rootcli),
1080                                 smbXcli_conn_protocol(rootcli->conn),
1081                                 0,
1082                                 0x20,
1083                                 targetcli);
1084                 if (!NT_STATUS_IS_OK(status)) {
1085                         d_printf("Unable to follow dfs referral [\\%s\\%s]\n",
1086                                  dfs_refs[count].server,
1087                                  dfs_refs[count].share);
1088                         continue;
1089                 } else {
1090                         extrapath = dfs_refs[count].extrapath;
1091                         break;
1092                 }
1093         }
1094
1095         /* No available referral server for the connection */
1096         if (*targetcli == NULL) {
1097                 TALLOC_FREE(dfs_refs);
1098                 return status;
1099         }
1100
1101         /* Make sure to recreate the original string including any wildcards. */
1102
1103         dfs_path = cli_dfs_make_full_path(ctx, rootcli, path);
1104         if (!dfs_path) {
1105                 TALLOC_FREE(dfs_refs);
1106                 return NT_STATUS_NO_MEMORY;
1107         }
1108         pathlen = strlen(dfs_path);
1109         consumed = MIN(pathlen, consumed);
1110         *pp_targetpath = talloc_strdup(ctx, &dfs_path[consumed]);
1111         if (!*pp_targetpath) {
1112                 TALLOC_FREE(dfs_refs);
1113                 return NT_STATUS_NO_MEMORY;
1114         }
1115         dfs_path[consumed] = '\0';
1116
1117         /*
1118          * *pp_targetpath is now the unconsumed part of the path.
1119          * dfs_path is now the consumed part of the path
1120          * (in \server\share\path format).
1121          */
1122
1123         if (extrapath && strlen(extrapath) > 0) {
1124                 /* EMC Celerra NAS version 5.6.50 (at least) doesn't appear to */
1125                 /* put the trailing \ on the path, so to be save we put one in if needed */
1126                 if (extrapath[strlen(extrapath)-1] != '\\' && **pp_targetpath != '\\') {
1127                         *pp_targetpath = talloc_asprintf(ctx,
1128                                                   "%s\\%s",
1129                                                   extrapath,
1130                                                   *pp_targetpath);
1131                 } else {
1132                         *pp_targetpath = talloc_asprintf(ctx,
1133                                                   "%s%s",
1134                                                   extrapath,
1135                                                   *pp_targetpath);
1136                 }
1137                 if (!*pp_targetpath) {
1138                         TALLOC_FREE(dfs_refs);
1139                         return NT_STATUS_NO_MEMORY;
1140                 }
1141         }
1142
1143         /* parse out the consumed mount path */
1144         /* trim off the \server\share\ */
1145
1146         ppath = dfs_path;
1147
1148         if (*ppath != '\\') {
1149                 d_printf("cli_resolve_path: "
1150                         "dfs_path (%s) not in correct format.\n",
1151                         dfs_path );
1152                 TALLOC_FREE(dfs_refs);
1153                 return NT_STATUS_NOT_FOUND;
1154         }
1155
1156         ppath++; /* Now pointing at start of server name. */
1157
1158         if ((ppath = strchr_m( dfs_path, '\\' )) == NULL) {
1159                 TALLOC_FREE(dfs_refs);
1160                 return NT_STATUS_NOT_FOUND;
1161         }
1162
1163         ppath++; /* Now pointing at start of share name. */
1164
1165         if ((ppath = strchr_m( ppath+1, '\\' )) == NULL) {
1166                 TALLOC_FREE(dfs_refs);
1167                 return NT_STATUS_NOT_FOUND;
1168         }
1169
1170         ppath++; /* Now pointing at path component. */
1171
1172         newmount = talloc_asprintf(ctx, "%s\\%s", mountpt, ppath );
1173         if (!newmount) {
1174                 TALLOC_FREE(dfs_refs);
1175                 return NT_STATUS_NOT_FOUND;
1176         }
1177
1178         cli_set_mntpoint(*targetcli, newmount);
1179
1180         /* Check for another dfs referral, note that we are not
1181            checking for loops here. */
1182
1183         if (!strequal(*pp_targetpath, "\\") && !strequal(*pp_targetpath, "/")) {
1184                 status = cli_resolve_path(ctx,
1185                                           newmount,
1186                                           dfs_auth_info,
1187                                           *targetcli,
1188                                           *pp_targetpath,
1189                                           &newcli,
1190                                           &newpath);
1191                 if (NT_STATUS_IS_OK(status)) {
1192                         /*
1193                          * When cli_resolve_path returns true here it's always
1194                          * returning the complete path in newpath, so we're done
1195                          * here.
1196                          */
1197                         *targetcli = newcli;
1198                         *pp_targetpath = newpath;
1199                         TALLOC_FREE(dfs_refs);
1200                         return status;
1201                 }
1202         }
1203
1204   done:
1205
1206         if (smbXcli_conn_protocol((*targetcli)->conn) >= PROTOCOL_SMB2_02) {
1207                 target_tcon = (*targetcli)->smb2.tcon;
1208         } else {
1209                 target_tcon = (*targetcli)->smb1.tcon;
1210         }
1211
1212         /* If returning true ensure we return a dfs root full path. */
1213         if (smbXcli_tcon_is_dfs_share(target_tcon)) {
1214                 dfs_path = talloc_strdup(ctx, *pp_targetpath);
1215                 if (!dfs_path) {
1216                         TALLOC_FREE(dfs_refs);
1217                         return NT_STATUS_NO_MEMORY;
1218                 }
1219                 *pp_targetpath = cli_dfs_make_full_path(ctx, *targetcli, dfs_path);
1220                 if (*pp_targetpath == NULL) {
1221                         TALLOC_FREE(dfs_refs);
1222                         return NT_STATUS_NO_MEMORY;
1223                 }
1224         }
1225
1226         TALLOC_FREE(dfs_refs);
1227         return NT_STATUS_OK;
1228 }
1229
1230 /********************************************************************
1231 ********************************************************************/
1232
1233 bool cli_check_msdfs_proxy(TALLOC_CTX *ctx,
1234                                 struct cli_state *cli,
1235                                 const char *sharename,
1236                                 char **pp_newserver,
1237                                 char **pp_newshare,
1238                                 bool force_encrypt,
1239                                 struct cli_credentials *creds)
1240 {
1241         struct client_dfs_referral *refs = NULL;
1242         size_t num_refs = 0;
1243         size_t consumed = 0;
1244         char *fullpath = NULL;
1245         bool res;
1246         struct smbXcli_tcon *orig_tcon = NULL;
1247         char *newextrapath = NULL;
1248         NTSTATUS status;
1249         const char *remote_name;
1250
1251         if (!cli || !sharename) {
1252                 return false;
1253         }
1254
1255         remote_name = smbXcli_conn_remote_name(cli->conn);
1256
1257         /* special case.  never check for a referral on the IPC$ share */
1258
1259         if (strequal(sharename, "IPC$")) {
1260                 return false;
1261         }
1262
1263         /* send a trans2_query_path_info to check for a referral */
1264
1265         fullpath = talloc_asprintf(ctx, "\\%s\\%s", remote_name, sharename);
1266         if (!fullpath) {
1267                 return false;
1268         }
1269
1270         /* Store tcon state. */
1271         if (cli_state_has_tcon(cli)) {
1272                 orig_tcon = cli_state_save_tcon(cli);
1273                 if (orig_tcon == NULL) {
1274                         return false;
1275                 }
1276         }
1277
1278         /* check for the referral */
1279
1280         if (!NT_STATUS_IS_OK(cli_tree_connect(cli, "IPC$", "IPC", NULL))) {
1281                 cli_state_restore_tcon(cli, orig_tcon);
1282                 return false;
1283         }
1284
1285         if (force_encrypt) {
1286                 status = cli_cm_force_encryption_creds(cli, creds, "IPC$");
1287                 if (!NT_STATUS_IS_OK(status)) {
1288                         cli_state_restore_tcon(cli, orig_tcon);
1289                         return false;
1290                 }
1291         }
1292
1293         status = cli_dfs_get_referral(ctx, cli, fullpath, &refs,
1294                                       &num_refs, &consumed);
1295         res = NT_STATUS_IS_OK(status);
1296
1297         status = cli_tdis(cli);
1298
1299         cli_state_restore_tcon(cli, orig_tcon);
1300
1301         if (!NT_STATUS_IS_OK(status)) {
1302                 return false;
1303         }
1304
1305         if (!res || !num_refs) {
1306                 return false;
1307         }
1308
1309         if (!refs[0].dfspath) {
1310                 return false;
1311         }
1312
1313         if (!split_dfs_path(ctx, refs[0].dfspath, pp_newserver,
1314                             pp_newshare, &newextrapath)) {
1315                 return false;
1316         }
1317
1318         /* check that this is not a self-referral */
1319
1320         if (strequal(remote_name, *pp_newserver) &&
1321                         strequal(sharename, *pp_newshare)) {
1322                 return false;
1323         }
1324
1325         return true;
1326 }