s3-param: Rename loadparm_s3_context -> loadparm_s3_helpers
[kai/samba.git] / source3 / smbd / filename.c
1 /*
2    Unix SMB/CIFS implementation.
3    filename handling routines
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 1999-2007
6    Copyright (C) Ying Chen 2000
7    Copyright (C) Volker Lendecke 2007
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 /*
24  * New hash table stat cache code added by Ying Chen.
25  */
26
27 #include "includes.h"
28 #include "system/filesys.h"
29 #include "fake_file.h"
30 #include "smbd/smbd.h"
31 #include "smbd/globals.h"
32
33 static NTSTATUS build_stream_path(TALLOC_CTX *mem_ctx,
34                                   connection_struct *conn,
35                                   const char *orig_path,
36                                   struct smb_filename *smb_fname);
37
38 /****************************************************************************
39  Mangle the 2nd name and check if it is then equal to the first name.
40 ****************************************************************************/
41
42 static bool mangled_equal(const char *name1,
43                         const char *name2,
44                         const struct share_params *p)
45 {
46         char mname[13];
47
48         if (!name_to_8_3(name2, mname, False, p)) {
49                 return False;
50         }
51         return strequal(name1, mname);
52 }
53
54 /****************************************************************************
55  Cope with the differing wildcard and non-wildcard error cases.
56 ****************************************************************************/
57
58 static NTSTATUS determine_path_error(const char *name,
59                         bool allow_wcard_last_component)
60 {
61         const char *p;
62
63         if (!allow_wcard_last_component) {
64                 /* Error code within a pathname. */
65                 return NT_STATUS_OBJECT_PATH_NOT_FOUND;
66         }
67
68         /* We're terminating here so we
69          * can be a little slower and get
70          * the error code right. Windows
71          * treats the last part of the pathname
72          * separately I think, so if the last
73          * component is a wildcard then we treat
74          * this ./ as "end of component" */
75
76         p = strchr(name, '/');
77
78         if (!p && (ms_has_wild(name) || ISDOT(name))) {
79                 /* Error code at the end of a pathname. */
80                 return NT_STATUS_OBJECT_NAME_INVALID;
81         } else {
82                 /* Error code within a pathname. */
83                 return NT_STATUS_OBJECT_PATH_NOT_FOUND;
84         }
85 }
86
87 static NTSTATUS check_for_dot_component(const struct smb_filename *smb_fname)
88 {
89         /* Ensure we catch all names with in "/."
90            this is disallowed under Windows and
91            in POSIX they've already been removed. */
92         const char *p = strstr(smb_fname->base_name, "/."); /*mb safe*/
93         if (p) {
94                 if (p[2] == '/') {
95                         /* Error code within a pathname. */
96                         return NT_STATUS_OBJECT_PATH_NOT_FOUND;
97                 } else if (p[2] == '\0') {
98                         /* Error code at the end of a pathname. */
99                         return NT_STATUS_OBJECT_NAME_INVALID;
100                 }
101         }
102         return NT_STATUS_OK;
103 }
104
105 /****************************************************************************
106  Optimization for common case where the missing part
107  is in the last component and the client already
108  sent the correct case.
109  Returns NT_STATUS_OK to mean continue the tree walk
110  (possibly with modified start pointer).
111  Any other NT_STATUS_XXX error means terminate the path
112  lookup here.
113 ****************************************************************************/
114
115 static NTSTATUS check_parent_exists(TALLOC_CTX *ctx,
116                                 connection_struct *conn,
117                                 bool posix_pathnames,
118                                 const struct smb_filename *smb_fname,
119                                 char **pp_dirpath,
120                                 char **pp_start)
121 {
122         struct smb_filename parent_fname;
123         const char *last_component = NULL;
124         NTSTATUS status;
125         int ret;
126
127         ZERO_STRUCT(parent_fname);
128         if (!parent_dirname(ctx, smb_fname->base_name,
129                                 &parent_fname.base_name,
130                                 &last_component)) {
131                 return NT_STATUS_NO_MEMORY;
132         }
133
134         /*
135          * If there was no parent component in
136          * smb_fname->base_name of the parent name
137          * contained a wildcard then don't do this
138          * optimization.
139          */
140         if ((smb_fname->base_name == last_component) ||
141                         ms_has_wild(parent_fname.base_name)) {
142                 return NT_STATUS_OK;
143         }
144
145         if (posix_pathnames) {
146                 ret = SMB_VFS_LSTAT(conn, &parent_fname);
147         } else {
148                 ret = SMB_VFS_STAT(conn, &parent_fname);
149         }
150
151         /* If the parent stat failed, just continue
152            with the normal tree walk. */
153
154         if (ret == -1) {
155                 return NT_STATUS_OK;
156         }
157
158         status = check_for_dot_component(&parent_fname);
159         if (!NT_STATUS_IS_OK(status)) {
160                 return status;
161         }
162
163         /* Parent exists - set "start" to be the
164          * last compnent to shorten the tree walk. */
165
166         /*
167          * Safe to use discard_const_p
168          * here as last_component points
169          * into our smb_fname->base_name.
170          */
171         *pp_start = discard_const_p(char, last_component);
172
173         /* Update dirpath. */
174         TALLOC_FREE(*pp_dirpath);
175         *pp_dirpath = talloc_strdup(ctx, parent_fname.base_name);
176         if (!*pp_dirpath) {
177                 return NT_STATUS_NO_MEMORY;
178         }
179
180         DEBUG(5,("check_parent_exists: name "
181                 "= %s, dirpath = %s, "
182                 "start = %s\n",
183                 smb_fname->base_name,
184                 *pp_dirpath,
185                 *pp_start));
186
187         return NT_STATUS_OK;
188 }
189
190 /****************************************************************************
191 This routine is called to convert names from the dos namespace to unix
192 namespace. It needs to handle any case conversions, mangling, format changes,
193 streams etc.
194
195 We assume that we have already done a chdir() to the right "root" directory
196 for this service.
197
198 The function will return an NTSTATUS error if some part of the name except for
199 the last part cannot be resolved, else NT_STATUS_OK.
200
201 Note NT_STATUS_OK doesn't mean the name exists or is valid, just that we
202 didn't get any fatal errors that should immediately terminate the calling SMB
203 processing whilst resolving.
204
205 If the UCF_SAVE_LCOMP flag is passed in, then the unmodified last component
206 of the pathname is set in smb_filename->original_lcomp.
207
208 If UCF_ALWAYS_ALLOW_WCARD_LCOMP is passed in, then a MS wildcard was detected
209 and should be allowed in the last component of the path only.
210
211 If the orig_path was a stream, smb_filename->base_name will point to the base
212 filename, and smb_filename->stream_name will point to the stream name.  If
213 orig_path was not a stream, then smb_filename->stream_name will be NULL.
214
215 On exit from unix_convert, the smb_filename->st stat struct will be populated
216 if the file exists and was found, if not this stat struct will be filled with
217 zeros (and this can be detected by checking for nlinks = 0, which can never be
218 true for any file).
219 ****************************************************************************/
220
221 NTSTATUS unix_convert(TALLOC_CTX *ctx,
222                       connection_struct *conn,
223                       const char *orig_path,
224                       struct smb_filename **smb_fname_out,
225                       uint32_t ucf_flags)
226 {
227         struct smb_filename *smb_fname = NULL;
228         char *start, *end;
229         char *dirpath = NULL;
230         char *stream = NULL;
231         bool component_was_mangled = False;
232         bool name_has_wildcard = False;
233         bool posix_pathnames = false;
234         bool allow_wcard_last_component =
235             (ucf_flags & UCF_ALWAYS_ALLOW_WCARD_LCOMP);
236         bool save_last_component = ucf_flags & UCF_SAVE_LCOMP;
237         NTSTATUS status;
238         int ret = -1;
239
240         *smb_fname_out = NULL;
241
242         smb_fname = talloc_zero(ctx, struct smb_filename);
243         if (smb_fname == NULL) {
244                 return NT_STATUS_NO_MEMORY;
245         }
246
247         if (conn->printer) {
248                 /* we don't ever use the filenames on a printer share as a
249                         filename - so don't convert them */
250                 if (!(smb_fname->base_name = talloc_strdup(smb_fname,
251                                                            orig_path))) {
252                         status = NT_STATUS_NO_MEMORY;
253                         goto err;
254                 }
255                 goto done;
256         }
257
258         DEBUG(5, ("unix_convert called on file \"%s\"\n", orig_path));
259
260         /*
261          * Conversion to basic unix format is already done in
262          * check_path_syntax().
263          */
264
265         /*
266          * Names must be relative to the root of the service - any leading /.
267          * and trailing /'s should have been trimmed by check_path_syntax().
268          */
269
270 #ifdef DEVELOPER
271         SMB_ASSERT(*orig_path != '/');
272 #endif
273
274         /*
275          * If we trimmed down to a single '\0' character
276          * then we should use the "." directory to avoid
277          * searching the cache, but not if we are in a
278          * printing share.
279          * As we know this is valid we can return true here.
280          */
281
282         if (!*orig_path) {
283                 if (!(smb_fname->base_name = talloc_strdup(smb_fname, "."))) {
284                         status = NT_STATUS_NO_MEMORY;
285                         goto err;
286                 }
287                 if (SMB_VFS_STAT(conn, smb_fname) != 0) {
288                         status = map_nt_error_from_unix(errno);
289                         goto err;
290                 }
291                 DEBUG(5, ("conversion finished \"\" -> %s\n",
292                           smb_fname->base_name));
293                 goto done;
294         }
295
296         if (orig_path[0] == '.' && (orig_path[1] == '/' ||
297                                 orig_path[1] == '\0')) {
298                 /* Start of pathname can't be "." only. */
299                 if (orig_path[1] == '\0' || orig_path[2] == '\0') {
300                         status = NT_STATUS_OBJECT_NAME_INVALID;
301                 } else {
302                         status =determine_path_error(&orig_path[2],
303                             allow_wcard_last_component);
304                 }
305                 goto err;
306         }
307
308         /* Start with the full orig_path as given by the caller. */
309         if (!(smb_fname->base_name = talloc_strdup(smb_fname, orig_path))) {
310                 DEBUG(0, ("talloc_strdup failed\n"));
311                 status = NT_STATUS_NO_MEMORY;
312                 goto err;
313         }
314
315         /*
316          * Large directory fix normalization. If we're case sensitive, and
317          * the case preserving parameters are set to "no", normalize the case of
318          * the incoming filename from the client WHETHER IT EXISTS OR NOT !
319          * This is in conflict with the current (3.0.20) man page, but is
320          * what people expect from the "large directory howto". I'll update
321          * the man page. Thanks to jht@samba.org for finding this. JRA.
322          */
323
324         if (conn->case_sensitive && !conn->case_preserve &&
325                         !conn->short_case_preserve) {
326                 strnorm(smb_fname->base_name, lp_defaultcase(SNUM(conn)));
327         }
328
329         /*
330          * Ensure saved_last_component is valid even if file exists.
331          */
332
333         if(save_last_component) {
334                 end = strrchr_m(smb_fname->base_name, '/');
335                 if (end) {
336                         smb_fname->original_lcomp = talloc_strdup(smb_fname,
337                                                                   end + 1);
338                 } else {
339                         smb_fname->original_lcomp =
340                             talloc_strdup(smb_fname, smb_fname->base_name);
341                 }
342                 if (smb_fname->original_lcomp == NULL) {
343                         status = NT_STATUS_NO_MEMORY;
344                         goto err;
345                 }
346         }
347
348         posix_pathnames = (lp_posix_pathnames() ||
349                                 (ucf_flags & UCF_POSIX_PATHNAMES));
350
351         /*
352          * Strip off the stream, and add it back when we're done with the
353          * base_name.
354          */
355         if (!posix_pathnames) {
356                 stream = strchr_m(smb_fname->base_name, ':');
357
358                 if (stream != NULL) {
359                         char *tmp = talloc_strdup(smb_fname, stream);
360                         if (tmp == NULL) {
361                                 status = NT_STATUS_NO_MEMORY;
362                                 goto err;
363                         }
364                         /*
365                          * Since this is actually pointing into
366                          * smb_fname->base_name this truncates base_name.
367                          */
368                         *stream = '\0';
369                         stream = tmp;
370                 }
371         }
372
373         start = smb_fname->base_name;
374
375         /*
376          * If we're providing case insensitive semantics or
377          * the underlying filesystem is case insensitive,
378          * then a case-normalized hit in the stat-cache is
379          * authoratitive. JRA.
380          *
381          * Note: We're only checking base_name.  The stream_name will be
382          * added and verified in build_stream_path().
383          */
384
385         if((!conn->case_sensitive || !(conn->fs_capabilities &
386                                        FILE_CASE_SENSITIVE_SEARCH)) &&
387             stat_cache_lookup(conn, posix_pathnames, &smb_fname->base_name, &dirpath, &start,
388                               &smb_fname->st)) {
389                 goto done;
390         }
391
392         /*
393          * Make sure "dirpath" is an allocated string, we use this for
394          * building the directories with talloc_asprintf and free it.
395          */
396
397         if ((dirpath == NULL) && (!(dirpath = talloc_strdup(ctx,"")))) {
398                 DEBUG(0, ("talloc_strdup failed\n"));
399                 status = NT_STATUS_NO_MEMORY;
400                 goto err;
401         }
402
403         /*
404          * If we have a wildcard we must walk the path to
405          * find where the error is, even if case sensitive
406          * is true.
407          */
408
409         name_has_wildcard = ms_has_wild(smb_fname->base_name);
410         if (name_has_wildcard && !allow_wcard_last_component) {
411                 /* Wildcard not valid anywhere. */
412                 status = NT_STATUS_OBJECT_NAME_INVALID;
413                 goto fail;
414         }
415
416         DEBUG(5,("unix_convert begin: name = %s, dirpath = %s, start = %s\n",
417                  smb_fname->base_name, dirpath, start));
418
419         if (!name_has_wildcard) {
420                 /*
421                  * stat the name - if it exists then we can add the stream back (if
422                  * there was one) and be done!
423                  */
424
425                 if (posix_pathnames) {
426                         ret = SMB_VFS_LSTAT(conn, smb_fname);
427                 } else {
428                         ret = SMB_VFS_STAT(conn, smb_fname);
429                 }
430
431                 if (ret == 0) {
432                         status = check_for_dot_component(smb_fname);
433                         if (!NT_STATUS_IS_OK(status)) {
434                                 goto fail;
435                         }
436                         /* Add the path (not including the stream) to the cache. */
437                         stat_cache_add(orig_path, smb_fname->base_name,
438                                        conn->case_sensitive);
439                         DEBUG(5,("conversion of base_name finished %s -> %s\n",
440                                  orig_path, smb_fname->base_name));
441                         goto done;
442                 }
443
444                 /* Stat failed - ensure we don't use it. */
445                 SET_STAT_INVALID(smb_fname->st);
446
447                 if (errno == ENOENT) {
448                         /* Optimization when creating a new file - only
449                            the last component doesn't exist. */
450                         status = check_parent_exists(ctx,
451                                                 conn,
452                                                 posix_pathnames,
453                                                 smb_fname,
454                                                 &dirpath,
455                                                 &start);
456                         if (!NT_STATUS_IS_OK(status)) {
457                                 goto fail;
458                         }
459                 }
460
461                 /*
462                  * A special case - if we don't have any wildcards or mangling chars and are case
463                  * sensitive or the underlying filesystem is case insensitive then searching
464                  * won't help.
465                  */
466
467                 if ((conn->case_sensitive || !(conn->fs_capabilities &
468                                         FILE_CASE_SENSITIVE_SEARCH)) &&
469                                 !mangle_is_mangled(smb_fname->base_name, conn->params)) {
470
471                         status = check_for_dot_component(smb_fname);
472                         if (!NT_STATUS_IS_OK(status)) {
473                                 goto fail;
474                         }
475
476                         /*
477                          * The stat failed. Could be ok as it could be
478                          * a new file.
479                          */
480
481                         if (errno == ENOTDIR || errno == ELOOP) {
482                                 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
483                                 goto fail;
484                         } else if (errno == ENOENT) {
485                                 /*
486                                  * Was it a missing last component ?
487                                  * or a missing intermediate component ?
488                                  */
489                                 struct smb_filename parent_fname;
490                                 const char *last_component = NULL;
491
492                                 ZERO_STRUCT(parent_fname);
493                                 if (!parent_dirname(ctx, smb_fname->base_name,
494                                                         &parent_fname.base_name,
495                                                         &last_component)) {
496                                         status = NT_STATUS_NO_MEMORY;
497                                         goto fail;
498                                 }
499                                 if (posix_pathnames) {
500                                         ret = SMB_VFS_LSTAT(conn, &parent_fname);
501                                 } else {
502                                         ret = SMB_VFS_STAT(conn, &parent_fname);
503                                 }
504                                 if (ret == -1) {
505                                         if (errno == ENOTDIR ||
506                                                         errno == ENOENT ||
507                                                         errno == ELOOP) {
508                                                 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
509                                                 goto fail;
510                                         }
511                                 }
512
513                                 /*
514                                  * Missing last component is ok - new file.
515                                  * Also deal with permission denied elsewhere.
516                                  * Just drop out to done.
517                                  */
518                                 goto done;
519                         }
520                 }
521         } else {
522                 /*
523                  * We have a wildcard in the pathname.
524                  *
525                  * Optimization for common case where the wildcard
526                  * is in the last component and the client already
527                  * sent the correct case.
528                  */
529                 status = check_parent_exists(ctx,
530                                         conn,
531                                         posix_pathnames,
532                                         smb_fname,
533                                         &dirpath,
534                                         &start);
535                 if (!NT_STATUS_IS_OK(status)) {
536                         goto fail;
537                 }
538         }
539
540         /*
541          * is_mangled() was changed to look at an entire pathname, not
542          * just a component. JRA.
543          */
544
545         if (mangle_is_mangled(start, conn->params)) {
546                 component_was_mangled = True;
547         }
548
549         /*
550          * Now we need to recursively match the name against the real
551          * directory structure.
552          */
553
554         /*
555          * Match each part of the path name separately, trying the names
556          * as is first, then trying to scan the directory for matching names.
557          */
558
559         for (; start ; start = (end?end+1:(char *)NULL)) {
560                 /*
561                  * Pinpoint the end of this section of the filename.
562                  */
563                 /* mb safe. '/' can't be in any encoded char. */
564                 end = strchr(start, '/');
565
566                 /*
567                  * Chop the name at this point.
568                  */
569                 if (end) {
570                         *end = 0;
571                 }
572
573                 if (save_last_component) {
574                         TALLOC_FREE(smb_fname->original_lcomp);
575                         smb_fname->original_lcomp = talloc_strdup(smb_fname,
576                                                         end ? end + 1 : start);
577                         if (!smb_fname->original_lcomp) {
578                                 DEBUG(0, ("talloc failed\n"));
579                                 status = NT_STATUS_NO_MEMORY;
580                                 goto err;
581                         }
582                 }
583
584                 /* The name cannot have a component of "." */
585
586                 if (ISDOT(start)) {
587                         if (!end)  {
588                                 /* Error code at the end of a pathname. */
589                                 status = NT_STATUS_OBJECT_NAME_INVALID;
590                         } else {
591                                 status = determine_path_error(end+1,
592                                                 allow_wcard_last_component);
593                         }
594                         goto fail;
595                 }
596
597                 /* The name cannot have a wildcard if it's not
598                    the last component. */
599
600                 name_has_wildcard = ms_has_wild(start);
601
602                 /* Wildcards never valid within a pathname. */
603                 if (name_has_wildcard && end) {
604                         status = NT_STATUS_OBJECT_NAME_INVALID;
605                         goto fail;
606                 }
607
608                 /* Skip the stat call if it's a wildcard end. */
609                 if (name_has_wildcard) {
610                         DEBUG(5,("Wildcard %s\n",start));
611                         goto done;
612                 }
613
614                 /*
615                  * Check if the name exists up to this point.
616                  */
617
618                 if (posix_pathnames) {
619                         ret = SMB_VFS_LSTAT(conn, smb_fname);
620                 } else {
621                         ret = SMB_VFS_STAT(conn, smb_fname);
622                 }
623
624                 if (ret == 0) {
625                         /*
626                          * It exists. it must either be a directory or this must
627                          * be the last part of the path for it to be OK.
628                          */
629                         if (end && !S_ISDIR(smb_fname->st.st_ex_mode)) {
630                                 /*
631                                  * An intermediate part of the name isn't
632                                  * a directory.
633                                  */
634                                 DEBUG(5,("Not a dir %s\n",start));
635                                 *end = '/';
636                                 /*
637                                  * We need to return the fact that the
638                                  * intermediate name resolution failed. This
639                                  * is used to return an error of ERRbadpath
640                                  * rather than ERRbadfile. Some Windows
641                                  * applications depend on the difference between
642                                  * these two errors.
643                                  */
644                                 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
645                                 goto fail;
646                         }
647
648                 } else {
649                         char *found_name = NULL;
650
651                         /* Stat failed - ensure we don't use it. */
652                         SET_STAT_INVALID(smb_fname->st);
653
654                         /*
655                          * Reset errno so we can detect
656                          * directory open errors.
657                          */
658                         errno = 0;
659
660                         /*
661                          * Try to find this part of the path in the directory.
662                          */
663
664                         if (name_has_wildcard ||
665                             (get_real_filename(conn, dirpath, start,
666                                                talloc_tos(),
667                                                &found_name) == -1)) {
668                                 char *unmangled;
669
670                                 if (end) {
671                                         /*
672                                          * An intermediate part of the name
673                                          * can't be found.
674                                          */
675                                         DEBUG(5,("Intermediate not found %s\n",
676                                                         start));
677                                         *end = '/';
678
679                                         /*
680                                          * We need to return the fact that the
681                                          * intermediate name resolution failed.
682                                          * This is used to return an error of
683                                          * ERRbadpath rather than ERRbadfile.
684                                          * Some Windows applications depend on
685                                          * the difference between these two
686                                          * errors.
687                                          */
688
689                                         /*
690                                          * ENOENT, ENOTDIR and ELOOP all map
691                                          * to NT_STATUS_OBJECT_PATH_NOT_FOUND
692                                          * in the filename walk.
693                                          */
694
695                                         if (errno == ENOENT ||
696                                                         errno == ENOTDIR ||
697                                                         errno == ELOOP) {
698                                                 status =
699                                                 NT_STATUS_OBJECT_PATH_NOT_FOUND;
700                                         }
701                                         else {
702                                                 status =
703                                                 map_nt_error_from_unix(errno);
704                                         }
705                                         goto fail;
706                                 }
707
708                                 /*
709                                  * ENOENT/EACCESS are the only valid errors
710                                  * here. EACCESS needs handling here for
711                                  * "dropboxes", i.e. directories where users
712                                  * can only put stuff with permission -wx.
713                                  */
714                                 if ((errno != 0) && (errno != ENOENT)
715                                     && (errno != EACCES)) {
716                                         /*
717                                          * ENOTDIR and ELOOP both map to
718                                          * NT_STATUS_OBJECT_PATH_NOT_FOUND
719                                          * in the filename walk.
720                                          */
721                                         if (errno == ENOTDIR ||
722                                                         errno == ELOOP) {
723                                                 status =
724                                                 NT_STATUS_OBJECT_PATH_NOT_FOUND;
725                                         } else {
726                                                 status =
727                                                 map_nt_error_from_unix(errno);
728                                         }
729                                         goto fail;
730                                 }
731
732                                 /*
733                                  * Just the last part of the name doesn't exist.
734                                  * We need to strupper() or strlower() it as
735                                  * this conversion may be used for file creation
736                                  * purposes. Fix inspired by
737                                  * Thomas Neumann <t.neumann@iku-ag.de>.
738                                  */
739                                 if (!conn->case_preserve ||
740                                     (mangle_is_8_3(start, False,
741                                                    conn->params) &&
742                                                  !conn->short_case_preserve)) {
743                                         strnorm(start,
744                                                 lp_defaultcase(SNUM(conn)));
745                                 }
746
747                                 /*
748                                  * check on the mangled stack to see if we can
749                                  * recover the base of the filename.
750                                  */
751
752                                 if (mangle_is_mangled(start, conn->params)
753                                     && mangle_lookup_name_from_8_3(ctx,
754                                                         start,
755                                                         &unmangled,
756                                                         conn->params)) {
757                                         char *tmp;
758                                         size_t start_ofs =
759                                             start - smb_fname->base_name;
760
761                                         if (*dirpath != '\0') {
762                                                 tmp = talloc_asprintf(
763                                                         smb_fname, "%s/%s",
764                                                         dirpath, unmangled);
765                                                 TALLOC_FREE(unmangled);
766                                         }
767                                         else {
768                                                 tmp = unmangled;
769                                         }
770                                         if (tmp == NULL) {
771                                                 DEBUG(0, ("talloc failed\n"));
772                                                 status = NT_STATUS_NO_MEMORY;
773                                                 goto err;
774                                         }
775                                         TALLOC_FREE(smb_fname->base_name);
776                                         smb_fname->base_name = tmp;
777                                         start =
778                                             smb_fname->base_name + start_ofs;
779                                         end = start + strlen(start);
780                                 }
781
782                                 DEBUG(5,("New file %s\n",start));
783                                 goto done;
784                         }
785
786
787                         /*
788                          * Restore the rest of the string. If the string was
789                          * mangled the size may have changed.
790                          */
791                         if (end) {
792                                 char *tmp;
793                                 size_t start_ofs =
794                                     start - smb_fname->base_name;
795
796                                 if (*dirpath != '\0') {
797                                         tmp = talloc_asprintf(smb_fname,
798                                                 "%s/%s/%s", dirpath,
799                                                 found_name, end+1);
800                                 }
801                                 else {
802                                         tmp = talloc_asprintf(smb_fname,
803                                                 "%s/%s", found_name,
804                                                 end+1);
805                                 }
806                                 if (tmp == NULL) {
807                                         DEBUG(0, ("talloc_asprintf failed\n"));
808                                         status = NT_STATUS_NO_MEMORY;
809                                         goto err;
810                                 }
811                                 TALLOC_FREE(smb_fname->base_name);
812                                 smb_fname->base_name = tmp;
813                                 start = smb_fname->base_name + start_ofs;
814                                 end = start + strlen(found_name);
815                                 *end = '\0';
816                         } else {
817                                 char *tmp;
818                                 size_t start_ofs =
819                                     start - smb_fname->base_name;
820
821                                 if (*dirpath != '\0') {
822                                         tmp = talloc_asprintf(smb_fname,
823                                                 "%s/%s", dirpath,
824                                                 found_name);
825                                 } else {
826                                         tmp = talloc_strdup(smb_fname,
827                                                 found_name);
828                                 }
829                                 if (tmp == NULL) {
830                                         DEBUG(0, ("talloc failed\n"));
831                                         status = NT_STATUS_NO_MEMORY;
832                                         goto err;
833                                 }
834                                 TALLOC_FREE(smb_fname->base_name);
835                                 smb_fname->base_name = tmp;
836                                 start = smb_fname->base_name + start_ofs;
837
838                                 /*
839                                  * We just scanned for, and found the end of
840                                  * the path. We must return a valid stat struct
841                                  * if it exists. JRA.
842                                  */
843
844                                 if (posix_pathnames) {
845                                         ret = SMB_VFS_LSTAT(conn, smb_fname);
846                                 } else {
847                                         ret = SMB_VFS_STAT(conn, smb_fname);
848                                 }
849
850                                 if (ret != 0) {
851                                         SET_STAT_INVALID(smb_fname->st);
852                                 }
853                         }
854
855                         TALLOC_FREE(found_name);
856                 } /* end else */
857
858 #ifdef DEVELOPER
859                 /*
860                  * This sucks!
861                  * We should never provide different behaviors
862                  * depending on DEVELOPER!!!
863                  */
864                 if (VALID_STAT(smb_fname->st)) {
865                         bool delete_pending;
866                         uint32_t name_hash;
867
868                         status = file_name_hash(conn,
869                                         smb_fname_str_dbg(smb_fname),
870                                         &name_hash);
871                         if (!NT_STATUS_IS_OK(status)) {
872                                 goto fail;
873                         }
874
875                         get_file_infos(vfs_file_id_from_sbuf(conn,
876                                                              &smb_fname->st),
877                                        name_hash,
878                                        &delete_pending, NULL);
879                         if (delete_pending) {
880                                 status = NT_STATUS_DELETE_PENDING;
881                                 goto fail;
882                         }
883                 }
884 #endif
885
886                 /*
887                  * Add to the dirpath that we have resolved so far.
888                  */
889
890                 if (*dirpath != '\0') {
891                         char *tmp = talloc_asprintf(ctx,
892                                         "%s/%s", dirpath, start);
893                         if (!tmp) {
894                                 DEBUG(0, ("talloc_asprintf failed\n"));
895                                 status = NT_STATUS_NO_MEMORY;
896                                 goto err;
897                         }
898                         TALLOC_FREE(dirpath);
899                         dirpath = tmp;
900                 }
901                 else {
902                         TALLOC_FREE(dirpath);
903                         if (!(dirpath = talloc_strdup(ctx,start))) {
904                                 DEBUG(0, ("talloc_strdup failed\n"));
905                                 status = NT_STATUS_NO_MEMORY;
906                                 goto err;
907                         }
908                 }
909
910                 /*
911                  * Cache the dirpath thus far. Don't cache a name with mangled
912                  * or wildcard components as this can change the size.
913                  */
914                 if(!component_was_mangled && !name_has_wildcard) {
915                         stat_cache_add(orig_path, dirpath,
916                                         conn->case_sensitive);
917                 }
918
919                 /*
920                  * Restore the / that we wiped out earlier.
921                  */
922                 if (end) {
923                         *end = '/';
924                 }
925         }
926
927         /*
928          * Cache the full path. Don't cache a name with mangled or wildcard
929          * components as this can change the size.
930          */
931
932         if(!component_was_mangled && !name_has_wildcard) {
933                 stat_cache_add(orig_path, smb_fname->base_name,
934                                conn->case_sensitive);
935         }
936
937         /*
938          * The name has been resolved.
939          */
940
941         DEBUG(5,("conversion finished %s -> %s\n", orig_path,
942                  smb_fname->base_name));
943
944  done:
945         /* Add back the stream if one was stripped off originally. */
946         if (stream != NULL) {
947                 smb_fname->stream_name = stream;
948
949                 /* Check path now that the base_name has been converted. */
950                 status = build_stream_path(ctx, conn, orig_path, smb_fname);
951                 if (!NT_STATUS_IS_OK(status)) {
952                         goto fail;
953                 }
954         }
955         TALLOC_FREE(dirpath);
956         *smb_fname_out = smb_fname;
957         return NT_STATUS_OK;
958  fail:
959         DEBUG(10, ("dirpath = [%s] start = [%s]\n", dirpath, start));
960         if (*dirpath != '\0') {
961                 smb_fname->base_name = talloc_asprintf(smb_fname, "%s/%s",
962                                                        dirpath, start);
963         } else {
964                 smb_fname->base_name = talloc_strdup(smb_fname, start);
965         }
966         if (!smb_fname->base_name) {
967                 DEBUG(0, ("talloc_asprintf failed\n"));
968                 status = NT_STATUS_NO_MEMORY;
969                 goto err;
970         }
971
972         *smb_fname_out = smb_fname;
973         TALLOC_FREE(dirpath);
974         return status;
975  err:
976         TALLOC_FREE(smb_fname);
977         return status;
978 }
979
980 /****************************************************************************
981  Ensure a path is not vetod.
982 ****************************************************************************/
983
984 NTSTATUS check_veto_path(connection_struct *conn, const char *name)
985 {
986         if (IS_VETO_PATH(conn, name))  {
987                 /* Is it not dot or dot dot. */
988                 if (!(ISDOT(name) || ISDOTDOT(name))) {
989                         DEBUG(5,("check_veto_path: file path name %s vetoed\n",
990                                                 name));
991                         return map_nt_error_from_unix(ENOENT);
992                 }
993         }
994         return NT_STATUS_OK;
995 }
996
997 /****************************************************************************
998  Check a filename - possibly calling check_reduced_name.
999  This is called by every routine before it allows an operation on a filename.
1000  It does any final confirmation necessary to ensure that the filename is
1001  a valid one for the user to access.
1002 ****************************************************************************/
1003
1004 NTSTATUS check_name(connection_struct *conn, const char *name)
1005 {
1006         NTSTATUS status = check_veto_path(conn, name);
1007
1008         if (!NT_STATUS_IS_OK(status)) {
1009                 return status;
1010         }
1011
1012         if (!lp_widelinks(SNUM(conn)) || !lp_symlinks(SNUM(conn))) {
1013                 status = check_reduced_name(conn,name);
1014                 if (!NT_STATUS_IS_OK(status)) {
1015                         DEBUG(5,("check_name: name %s failed with %s\n",name,
1016                                                 nt_errstr(status)));
1017                         return status;
1018                 }
1019         }
1020
1021         return NT_STATUS_OK;
1022 }
1023
1024 /****************************************************************************
1025  Must be called as root. Creates the struct privilege_paths
1026  attached to the struct smb_request if this call is successful.
1027 ****************************************************************************/
1028
1029 static NTSTATUS check_name_with_privilege(connection_struct *conn,
1030                 struct smb_request *smbreq,
1031                 const char *name)
1032 {
1033         NTSTATUS status = check_veto_path(conn, name);
1034
1035         if (!NT_STATUS_IS_OK(status)) {
1036                 return status;
1037         }
1038         return check_reduced_name_with_privilege(conn,
1039                         name,
1040                         smbreq);
1041 }
1042
1043 /****************************************************************************
1044  Check if two filenames are equal.
1045  This needs to be careful about whether we are case sensitive.
1046 ****************************************************************************/
1047
1048 static bool fname_equal(const char *name1, const char *name2,
1049                 bool case_sensitive)
1050 {
1051         /* Normal filename handling */
1052         if (case_sensitive) {
1053                 return(strcmp(name1,name2) == 0);
1054         }
1055
1056         return(strequal(name1,name2));
1057 }
1058
1059 /****************************************************************************
1060  Scan a directory to find a filename, matching without case sensitivity.
1061  If the name looks like a mangled name then try via the mangling functions
1062 ****************************************************************************/
1063
1064 static int get_real_filename_full_scan(connection_struct *conn,
1065                                        const char *path, const char *name,
1066                                        bool mangled,
1067                                        TALLOC_CTX *mem_ctx, char **found_name)
1068 {
1069         struct smb_Dir *cur_dir;
1070         const char *dname = NULL;
1071         char *talloced = NULL;
1072         char *unmangled_name = NULL;
1073         long curpos;
1074
1075         /* handle null paths */
1076         if ((path == NULL) || (*path == 0)) {
1077                 path = ".";
1078         }
1079
1080         /* If we have a case-sensitive filesystem, it doesn't do us any
1081          * good to search for a name. If a case variation of the name was
1082          * there, then the original stat(2) would have found it.
1083          */
1084         if (!mangled && !(conn->fs_capabilities & FILE_CASE_SENSITIVE_SEARCH)) {
1085                 errno = ENOENT;
1086                 return -1;
1087         }
1088
1089         /*
1090          * The incoming name can be mangled, and if we de-mangle it
1091          * here it will not compare correctly against the filename (name2)
1092          * read from the directory and then mangled by the name_to_8_3()
1093          * call. We need to mangle both names or neither.
1094          * (JRA).
1095          *
1096          * Fix for bug found by Dina Fine. If in case sensitive mode then
1097          * the mangle cache is no good (3 letter extension could be wrong
1098          * case - so don't demangle in this case - leave as mangled and
1099          * allow the mangling of the directory entry read (which is done
1100          * case insensitively) to match instead. This will lead to more
1101          * false positive matches but we fail completely without it. JRA.
1102          */
1103
1104         if (mangled && !conn->case_sensitive) {
1105                 mangled = !mangle_lookup_name_from_8_3(talloc_tos(), name,
1106                                                        &unmangled_name,
1107                                                        conn->params);
1108                 if (!mangled) {
1109                         /* Name is now unmangled. */
1110                         name = unmangled_name;
1111                 }
1112         }
1113
1114         /* open the directory */
1115         if (!(cur_dir = OpenDir(talloc_tos(), conn, path, NULL, 0))) {
1116                 DEBUG(3,("scan dir didn't open dir [%s]\n",path));
1117                 TALLOC_FREE(unmangled_name);
1118                 return -1;
1119         }
1120
1121         /* now scan for matching names */
1122         curpos = 0;
1123         while ((dname = ReadDirName(cur_dir, &curpos, NULL, &talloced))) {
1124
1125                 /* Is it dot or dot dot. */
1126                 if (ISDOT(dname) || ISDOTDOT(dname)) {
1127                         TALLOC_FREE(talloced);
1128                         continue;
1129                 }
1130
1131                 /*
1132                  * At this point dname is the unmangled name.
1133                  * name is either mangled or not, depending on the state
1134                  * of the "mangled" variable. JRA.
1135                  */
1136
1137                 /*
1138                  * Check mangled name against mangled name, or unmangled name
1139                  * against unmangled name.
1140                  */
1141
1142                 if ((mangled && mangled_equal(name,dname,conn->params)) ||
1143                         fname_equal(name, dname, conn->case_sensitive)) {
1144                         /* we've found the file, change it's name and return */
1145                         *found_name = talloc_strdup(mem_ctx, dname);
1146                         TALLOC_FREE(unmangled_name);
1147                         TALLOC_FREE(cur_dir);
1148                         if (!*found_name) {
1149                                 errno = ENOMEM;
1150                                 TALLOC_FREE(talloced);
1151                                 return -1;
1152                         }
1153                         TALLOC_FREE(talloced);
1154                         return 0;
1155                 }
1156                 TALLOC_FREE(talloced);
1157         }
1158
1159         TALLOC_FREE(unmangled_name);
1160         TALLOC_FREE(cur_dir);
1161         errno = ENOENT;
1162         return -1;
1163 }
1164
1165 /****************************************************************************
1166  Wrapper around the vfs get_real_filename and the full directory scan
1167  fallback.
1168 ****************************************************************************/
1169
1170 int get_real_filename(connection_struct *conn, const char *path,
1171                       const char *name, TALLOC_CTX *mem_ctx,
1172                       char **found_name)
1173 {
1174         int ret;
1175         bool mangled;
1176
1177         mangled = mangle_is_mangled(name, conn->params);
1178
1179         if (mangled) {
1180                 return get_real_filename_full_scan(conn, path, name, mangled,
1181                                                    mem_ctx, found_name);
1182         }
1183
1184         /* Try the vfs first to take advantage of case-insensitive stat. */
1185         ret = SMB_VFS_GET_REAL_FILENAME(conn, path, name, mem_ctx, found_name);
1186
1187         /*
1188          * If the case-insensitive stat was successful, or returned an error
1189          * other than EOPNOTSUPP then there is no need to fall back on the
1190          * full directory scan.
1191          */
1192         if (ret == 0 || (ret == -1 && errno != EOPNOTSUPP)) {
1193                 return ret;
1194         }
1195
1196         return get_real_filename_full_scan(conn, path, name, mangled, mem_ctx,
1197                                            found_name);
1198 }
1199
1200 static NTSTATUS build_stream_path(TALLOC_CTX *mem_ctx,
1201                                   connection_struct *conn,
1202                                   const char *orig_path,
1203                                   struct smb_filename *smb_fname)
1204 {
1205         NTSTATUS status;
1206         unsigned int i, num_streams = 0;
1207         struct stream_struct *streams = NULL;
1208
1209         if (SMB_VFS_STAT(conn, smb_fname) == 0) {
1210                 DEBUG(10, ("'%s' exists\n", smb_fname_str_dbg(smb_fname)));
1211                 return NT_STATUS_OK;
1212         }
1213
1214         if (errno != ENOENT) {
1215                 DEBUG(10, ("vfs_stat failed: %s\n", strerror(errno)));
1216                 status = map_nt_error_from_unix(errno);
1217                 goto fail;
1218         }
1219
1220         /* Fall back to a case-insensitive scan of all streams on the file. */
1221         status = vfs_streaminfo(conn, NULL, smb_fname->base_name, mem_ctx,
1222                                 &num_streams, &streams);
1223
1224         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1225                 SET_STAT_INVALID(smb_fname->st);
1226                 return NT_STATUS_OK;
1227         }
1228
1229         if (!NT_STATUS_IS_OK(status)) {
1230                 DEBUG(10, ("vfs_streaminfo failed: %s\n", nt_errstr(status)));
1231                 goto fail;
1232         }
1233
1234         for (i=0; i<num_streams; i++) {
1235                 DEBUG(10, ("comparing [%s] and [%s]: ",
1236                            smb_fname->stream_name, streams[i].name));
1237                 if (fname_equal(smb_fname->stream_name, streams[i].name,
1238                                 conn->case_sensitive)) {
1239                         DEBUGADD(10, ("equal\n"));
1240                         break;
1241                 }
1242                 DEBUGADD(10, ("not equal\n"));
1243         }
1244
1245         /* Couldn't find the stream. */
1246         if (i == num_streams) {
1247                 SET_STAT_INVALID(smb_fname->st);
1248                 TALLOC_FREE(streams);
1249                 return NT_STATUS_OK;
1250         }
1251
1252         DEBUG(10, ("case insensitive stream. requested: %s, actual: %s\n",
1253                 smb_fname->stream_name, streams[i].name));
1254
1255
1256         TALLOC_FREE(smb_fname->stream_name);
1257         smb_fname->stream_name = talloc_strdup(smb_fname, streams[i].name);
1258         if (smb_fname->stream_name == NULL) {
1259                 status = NT_STATUS_NO_MEMORY;
1260                 goto fail;
1261         }
1262
1263         SET_STAT_INVALID(smb_fname->st);
1264
1265         if (SMB_VFS_STAT(conn, smb_fname) == 0) {
1266                 DEBUG(10, ("'%s' exists\n", smb_fname_str_dbg(smb_fname)));
1267         }
1268         status = NT_STATUS_OK;
1269  fail:
1270         TALLOC_FREE(streams);
1271         return status;
1272 }
1273
1274 /**
1275  * Go through all the steps to validate a filename.
1276  *
1277  * @param ctx           talloc_ctx to allocate memory with.
1278  * @param conn          connection struct for vfs calls.
1279  * @param dfs_path      Whether this path requires dfs resolution.
1280  * @param smbreq        SMB request if we're using privileges.
1281  * @param name_in       The unconverted name.
1282  * @param ucf_flags     flags to pass through to unix_convert().
1283  *                      UCF_ALWAYS_ALLOW_WCARD_LCOMP will be OR'd in if
1284  *                      p_cont_wcard != NULL and is true and
1285  *                      UCF_COND_ALLOW_WCARD_LCOMP.
1286  * @param p_cont_wcard  If not NULL, will be set to true if the dfs path
1287  *                      resolution detects a wildcard.
1288  * @param pp_smb_fname  The final converted name will be allocated if the
1289  *                      return is NT_STATUS_OK.
1290  *
1291  * @return NT_STATUS_OK if all operations completed succesfully, appropriate
1292  *         error otherwise.
1293  */
1294 static NTSTATUS filename_convert_internal(TALLOC_CTX *ctx,
1295                                 connection_struct *conn,
1296                                 bool dfs_path,
1297                                 struct smb_request *smbreq,
1298                                 const char *name_in,
1299                                 uint32_t ucf_flags,
1300                                 bool *ppath_contains_wcard,
1301                                 struct smb_filename **pp_smb_fname)
1302 {
1303         NTSTATUS status;
1304         bool allow_wcards = (ucf_flags & (UCF_COND_ALLOW_WCARD_LCOMP|UCF_ALWAYS_ALLOW_WCARD_LCOMP));
1305         char *fname = NULL;
1306
1307         *pp_smb_fname = NULL;
1308
1309         status = resolve_dfspath_wcard(ctx, conn,
1310                                 dfs_path,
1311                                 name_in,
1312                                 allow_wcards,
1313                                 !conn->sconn->using_smb2,
1314                                 &fname,
1315                                 ppath_contains_wcard);
1316         if (!NT_STATUS_IS_OK(status)) {
1317                 DEBUG(10,("filename_convert_internal: resolve_dfspath failed "
1318                         "for name %s with %s\n",
1319                         name_in,
1320                         nt_errstr(status) ));
1321                 return status;
1322         }
1323
1324         if (is_fake_file_path(name_in)) {
1325                 SMB_STRUCT_STAT st;
1326                 ZERO_STRUCT(st);
1327                 st.st_ex_nlink = 1;
1328                 status = create_synthetic_smb_fname_split(ctx,
1329                                                           name_in,
1330                                                           &st,
1331                                                           pp_smb_fname);
1332                 return status;
1333         }
1334
1335         /*
1336          * If the caller conditionally allows wildcard lookups, only add the
1337          * always allow if the path actually does contain a wildcard.
1338          */
1339         if (ucf_flags & UCF_COND_ALLOW_WCARD_LCOMP &&
1340             ppath_contains_wcard != NULL && *ppath_contains_wcard) {
1341                 ucf_flags |= UCF_ALWAYS_ALLOW_WCARD_LCOMP;
1342         }
1343
1344         status = unix_convert(ctx, conn, fname, pp_smb_fname, ucf_flags);
1345         if (!NT_STATUS_IS_OK(status)) {
1346                 DEBUG(10,("filename_convert_internal: unix_convert failed "
1347                         "for name %s with %s\n",
1348                         fname,
1349                         nt_errstr(status) ));
1350                 return status;
1351         }
1352
1353         if ((ucf_flags & UCF_UNIX_NAME_LOOKUP) &&
1354                         VALID_STAT((*pp_smb_fname)->st) &&
1355                         S_ISLNK((*pp_smb_fname)->st.st_ex_mode)) {
1356                 return check_veto_path(conn, (*pp_smb_fname)->base_name);
1357         }
1358
1359         if (!smbreq) {
1360                 status = check_name(conn, (*pp_smb_fname)->base_name);
1361         } else {
1362                 status = check_name_with_privilege(conn, smbreq, (*pp_smb_fname)->base_name);
1363         }
1364         if (!NT_STATUS_IS_OK(status)) {
1365                 DEBUG(3,("filename_convert_internal: check_name failed "
1366                         "for name %s with %s\n",
1367                         smb_fname_str_dbg(*pp_smb_fname),
1368                         nt_errstr(status) ));
1369                 TALLOC_FREE(*pp_smb_fname);
1370                 return status;
1371         }
1372
1373         return status;
1374 }
1375
1376 /*
1377  * Go through all the steps to validate a filename.
1378  * Non-root version.
1379  */
1380
1381 NTSTATUS filename_convert(TALLOC_CTX *ctx,
1382                                 connection_struct *conn,
1383                                 bool dfs_path,
1384                                 const char *name_in,
1385                                 uint32_t ucf_flags,
1386                                 bool *ppath_contains_wcard,
1387                                 struct smb_filename **pp_smb_fname)
1388 {
1389         return filename_convert_internal(ctx,
1390                                         conn,
1391                                         dfs_path,
1392                                         NULL,
1393                                         name_in,
1394                                         ucf_flags,
1395                                         ppath_contains_wcard,
1396                                         pp_smb_fname);
1397 }
1398
1399 /*
1400  * Go through all the steps to validate a filename.
1401  * root (privileged) version.
1402  */
1403
1404 NTSTATUS filename_convert_with_privilege(TALLOC_CTX *ctx,
1405                                 connection_struct *conn,
1406                                 struct smb_request *smbreq,
1407                                 const char *name_in,
1408                                 uint32_t ucf_flags,
1409                                 bool *ppath_contains_wcard,
1410                                 struct smb_filename **pp_smb_fname)
1411 {
1412         return filename_convert_internal(ctx,
1413                                         conn,
1414                                         smbreq->flags2 & FLAGS2_DFS_PATHNAMES,
1415                                         smbreq,
1416                                         name_in,
1417                                         ucf_flags,
1418                                         ppath_contains_wcard,
1419                                         pp_smb_fname);
1420 }