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