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