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