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