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