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