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