Remove call into reduce_name if case sensitive. This allows us to pass
[ira/wip.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
29 static NTSTATUS build_stream_path(TALLOC_CTX *mem_ctx,
30                                   connection_struct *conn,
31                                   const char *orig_path,
32                                   struct smb_filename *smb_fname);
33
34 /****************************************************************************
35  Mangle the 2nd name and check if it is then equal to the first name.
36 ****************************************************************************/
37
38 static bool mangled_equal(const char *name1,
39                         const char *name2,
40                         const struct share_params *p)
41 {
42         char mname[13];
43
44         if (!name_to_8_3(name2, mname, False, p)) {
45                 return False;
46         }
47         return strequal(name1, mname);
48 }
49
50 /****************************************************************************
51  Cope with the differing wildcard and non-wildcard error cases.
52 ****************************************************************************/
53
54 static NTSTATUS determine_path_error(const char *name,
55                         bool allow_wcard_last_component)
56 {
57         const char *p;
58
59         if (!allow_wcard_last_component) {
60                 /* Error code within a pathname. */
61                 return NT_STATUS_OBJECT_PATH_NOT_FOUND;
62         }
63
64         /* We're terminating here so we
65          * can be a little slower and get
66          * the error code right. Windows
67          * treats the last part of the pathname
68          * separately I think, so if the last
69          * component is a wildcard then we treat
70          * this ./ as "end of component" */
71
72         p = strchr(name, '/');
73
74         if (!p && (ms_has_wild(name) || ISDOT(name))) {
75                 /* Error code at the end of a pathname. */
76                 return NT_STATUS_OBJECT_NAME_INVALID;
77         } else {
78                 /* Error code within a pathname. */
79                 return NT_STATUS_OBJECT_PATH_NOT_FOUND;
80         }
81 }
82
83 /****************************************************************************
84 This routine is called to convert names from the dos namespace to unix
85 namespace. It needs to handle any case conversions, mangling, format changes,
86 streams etc.
87
88 We assume that we have already done a chdir() to the right "root" directory
89 for this service.
90
91 The function will return an NTSTATUS error if some part of the name except for
92 the last part cannot be resolved, else NT_STATUS_OK.
93
94 Note NT_STATUS_OK doesn't mean the name exists or is valid, just that we
95 didn't get any fatal errors that should immediately terminate the calling SMB
96 processing whilst resolving.
97
98 If the UCF_SAVE_LCOMP flag is passed in, then the unmodified last component
99 of the pathname is set in smb_filename->original_lcomp.
100
101 If UCF_ALWAYS_ALLOW_WCARD_LCOMP is passed in, then a MS wildcard was detected
102 and should be allowed in the last component of the path only.
103
104 If the orig_path was a stream, smb_filename->base_name will point to the base
105 filename, and smb_filename->stream_name will point to the stream name.  If
106 orig_path was not a stream, then smb_filename->stream_name will be NULL.
107
108 On exit from unix_convert, the smb_filename->st stat struct will be populated
109 if the file exists and was found, if not this stat struct will be filled with
110 zeros (and this can be detected by checking for nlinks = 0, which can never be
111 true for any file).
112 ****************************************************************************/
113
114 NTSTATUS unix_convert(TALLOC_CTX *ctx,
115                       connection_struct *conn,
116                       const char *orig_path,
117                       struct smb_filename **smb_fname_out,
118                       uint32_t ucf_flags)
119 {
120         struct smb_filename *smb_fname = NULL;
121         char *start, *end;
122         char *dirpath = NULL;
123         char *stream = NULL;
124         bool component_was_mangled = False;
125         bool name_has_wildcard = False;
126         bool posix_pathnames = false;
127         bool allow_wcard_last_component =
128             (ucf_flags & UCF_ALWAYS_ALLOW_WCARD_LCOMP);
129         bool save_last_component = ucf_flags & UCF_SAVE_LCOMP;
130         NTSTATUS status;
131         int ret = -1;
132
133         *smb_fname_out = NULL;
134
135         smb_fname = talloc_zero(ctx, struct smb_filename);
136         if (smb_fname == NULL) {
137                 return NT_STATUS_NO_MEMORY;
138         }
139
140         if (conn->printer) {
141                 /* we don't ever use the filenames on a printer share as a
142                         filename - so don't convert them */
143                 if (!(smb_fname->base_name = talloc_strdup(smb_fname,
144                                                            orig_path))) {
145                         status = NT_STATUS_NO_MEMORY;
146                         goto err;
147                 }
148                 goto done;
149         }
150
151         DEBUG(5, ("unix_convert called on file \"%s\"\n", orig_path));
152
153         /*
154          * Conversion to basic unix format is already done in
155          * check_path_syntax().
156          */
157
158         /*
159          * Names must be relative to the root of the service - any leading /.
160          * and trailing /'s should have been trimmed by check_path_syntax().
161          */
162
163 #ifdef DEVELOPER
164         SMB_ASSERT(*orig_path != '/');
165 #endif
166
167         /*
168          * If we trimmed down to a single '\0' character
169          * then we should use the "." directory to avoid
170          * searching the cache, but not if we are in a
171          * printing share.
172          * As we know this is valid we can return true here.
173          */
174
175         if (!*orig_path) {
176                 if (!(smb_fname->base_name = talloc_strdup(smb_fname, "."))) {
177                         status = NT_STATUS_NO_MEMORY;
178                         goto err;
179                 }
180                 if (SMB_VFS_STAT(conn, smb_fname) != 0) {
181                         status = map_nt_error_from_unix(errno);
182                         goto err;
183                 }
184                 DEBUG(5, ("conversion finished \"\" -> %s\n",
185                           smb_fname->base_name));
186                 goto done;
187         }
188
189         if (orig_path[0] == '.' && (orig_path[1] == '/' ||
190                                 orig_path[1] == '\0')) {
191                 /* Start of pathname can't be "." only. */
192                 if (orig_path[1] == '\0' || orig_path[2] == '\0') {
193                         status = NT_STATUS_OBJECT_NAME_INVALID;
194                 } else {
195                         status =determine_path_error(&orig_path[2],
196                             allow_wcard_last_component);
197                 }
198                 goto err;
199         }
200
201         /* Start with the full orig_path as given by the caller. */
202         if (!(smb_fname->base_name = talloc_strdup(smb_fname, orig_path))) {
203                 DEBUG(0, ("talloc_strdup failed\n"));
204                 status = NT_STATUS_NO_MEMORY;
205                 goto err;
206         }
207
208         /*
209          * Large directory fix normalization. If we're case sensitive, and
210          * the case preserving parameters are set to "no", normalize the case of
211          * the incoming filename from the client WHETHER IT EXISTS OR NOT !
212          * This is in conflict with the current (3.0.20) man page, but is
213          * what people expect from the "large directory howto". I'll update
214          * the man page. Thanks to jht@samba.org for finding this. JRA.
215          */
216
217         if (conn->case_sensitive && !conn->case_preserve &&
218                         !conn->short_case_preserve) {
219                 strnorm(smb_fname->base_name, lp_defaultcase(SNUM(conn)));
220         }
221
222         /*
223          * Ensure saved_last_component is valid even if file exists.
224          */
225
226         if(save_last_component) {
227                 end = strrchr_m(smb_fname->base_name, '/');
228                 if (end) {
229                         smb_fname->original_lcomp = talloc_strdup(smb_fname,
230                                                                   end + 1);
231                 } else {
232                         smb_fname->original_lcomp =
233                             talloc_strdup(smb_fname, smb_fname->base_name);
234                 }
235                 if (smb_fname->original_lcomp == NULL) {
236                         status = NT_STATUS_NO_MEMORY;
237                         goto err;
238                 }
239         }
240
241         posix_pathnames = (lp_posix_pathnames() ||
242                                 (ucf_flags & UCF_POSIX_PATHNAMES));
243
244         /*
245          * Strip off the stream, and add it back when we're done with the
246          * base_name.
247          */
248         if (!posix_pathnames) {
249                 stream = strchr_m(smb_fname->base_name, ':');
250
251                 if (stream != NULL) {
252                         char *tmp = talloc_strdup(smb_fname, stream);
253                         if (tmp == NULL) {
254                                 status = NT_STATUS_NO_MEMORY;
255                                 goto err;
256                         }
257                         /*
258                          * Since this is actually pointing into
259                          * smb_fname->base_name this truncates base_name.
260                          */
261                         *stream = '\0';
262                         stream = tmp;
263                 }
264         }
265
266         start = smb_fname->base_name;
267
268         /*
269          * If we're providing case insentive semantics or
270          * the underlying filesystem is case insensitive,
271          * then a case-normalized hit in the stat-cache is
272          * authoratitive. JRA.
273          *
274          * Note: We're only checking base_name.  The stream_name will be
275          * added and verified in build_stream_path().
276          */
277
278         if((!conn->case_sensitive || !(conn->fs_capabilities &
279                                        FILE_CASE_SENSITIVE_SEARCH)) &&
280             stat_cache_lookup(conn, &smb_fname->base_name, &dirpath, &start,
281                               &smb_fname->st)) {
282                 goto done;
283         }
284
285         /*
286          * Make sure "dirpath" is an allocated string, we use this for
287          * building the directories with asprintf and free it.
288          */
289
290         if ((dirpath == NULL) && (!(dirpath = talloc_strdup(ctx,"")))) {
291                 DEBUG(0, ("talloc_strdup failed\n"));
292                 status = NT_STATUS_NO_MEMORY;
293                 goto err;
294         }
295
296         /*
297          * stat the name - if it exists then we can add the stream back (if
298          * there was one) and be done!
299          */
300
301         if (posix_pathnames) {
302                 ret = SMB_VFS_LSTAT(conn, smb_fname);
303         } else {
304                 ret = SMB_VFS_STAT(conn, smb_fname);
305         }
306
307         if (ret == 0) {
308                 /* Ensure we catch all names with in "/."
309                    this is disallowed under Windows. */
310                 const char *p = strstr(smb_fname->base_name, "/."); /*mb safe*/
311                 if (p) {
312                         if (p[2] == '/') {
313                                 /* Error code within a pathname. */
314                                 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
315                                 goto fail;
316                         } else if (p[2] == '\0') {
317                                 /* Error code at the end of a pathname. */
318                                 status = NT_STATUS_OBJECT_NAME_INVALID;
319                                 goto fail;
320                         }
321                 }
322                 /* Add the path (not including the stream) to the cache. */
323                 stat_cache_add(orig_path, smb_fname->base_name,
324                                conn->case_sensitive);
325                 DEBUG(5,("conversion of base_name finished %s -> %s\n",
326                          orig_path, smb_fname->base_name));
327                 goto done;
328         }
329
330         DEBUG(5,("unix_convert begin: name = %s, dirpath = %s, start = %s\n",
331                  smb_fname->base_name, dirpath, start));
332
333         /*
334          * A special case - if we don't have any mangling chars and are case
335          * sensitive or the underlying filesystem is case insentive then searching
336          * won't help.
337          */
338
339         if ((conn->case_sensitive || !(conn->fs_capabilities &
340                                        FILE_CASE_SENSITIVE_SEARCH)) &&
341             !mangle_is_mangled(smb_fname->base_name, conn->params)) {
342                 goto done;
343         }
344
345         /*
346          * is_mangled() was changed to look at an entire pathname, not
347          * just a component. JRA.
348          */
349
350         if (mangle_is_mangled(start, conn->params)) {
351                 component_was_mangled = True;
352         }
353
354         /*
355          * Now we need to recursively match the name against the real
356          * directory structure.
357          */
358
359         /*
360          * Match each part of the path name separately, trying the names
361          * as is first, then trying to scan the directory for matching names.
362          */
363
364         for (; start ; start = (end?end+1:(char *)NULL)) {
365                 /*
366                  * Pinpoint the end of this section of the filename.
367                  */
368                 /* mb safe. '/' can't be in any encoded char. */
369                 end = strchr(start, '/');
370
371                 /*
372                  * Chop the name at this point.
373                  */
374                 if (end) {
375                         *end = 0;
376                 }
377
378                 if (save_last_component) {
379                         TALLOC_FREE(smb_fname->original_lcomp);
380                         smb_fname->original_lcomp = talloc_strdup(smb_fname,
381                                                         end ? end + 1 : start);
382                         if (!smb_fname->original_lcomp) {
383                                 DEBUG(0, ("talloc failed\n"));
384                                 status = NT_STATUS_NO_MEMORY;
385                                 goto err;
386                         }
387                 }
388
389                 /* The name cannot have a component of "." */
390
391                 if (ISDOT(start)) {
392                         if (!end)  {
393                                 /* Error code at the end of a pathname. */
394                                 status = NT_STATUS_OBJECT_NAME_INVALID;
395                         } else {
396                                 status = determine_path_error(end+1,
397                                                 allow_wcard_last_component);
398                         }
399                         goto fail;
400                 }
401
402                 /* The name cannot have a wildcard if it's not
403                    the last component. */
404
405                 name_has_wildcard = ms_has_wild(start);
406
407                 /* Wildcard not valid anywhere. */
408                 if (name_has_wildcard && !allow_wcard_last_component) {
409                         status = NT_STATUS_OBJECT_NAME_INVALID;
410                         goto fail;
411                 }
412
413                 /* Wildcards never valid within a pathname. */
414                 if (name_has_wildcard && end) {
415                         status = NT_STATUS_OBJECT_NAME_INVALID;
416                         goto fail;
417                 }
418
419                 /*
420                  * Check if the name exists up to this point.
421                  */
422
423                 if (posix_pathnames) {
424                         ret = SMB_VFS_LSTAT(conn, smb_fname);
425                 } else {
426                         ret = SMB_VFS_STAT(conn, smb_fname);
427                 }
428
429                 if (ret == 0) {
430                         /*
431                          * It exists. it must either be a directory or this must
432                          * be the last part of the path for it to be OK.
433                          */
434                         if (end && !S_ISDIR(smb_fname->st.st_ex_mode)) {
435                                 /*
436                                  * An intermediate part of the name isn't
437                                  * a directory.
438                                  */
439                                 DEBUG(5,("Not a dir %s\n",start));
440                                 *end = '/';
441                                 /*
442                                  * We need to return the fact that the
443                                  * intermediate name resolution failed. This
444                                  * is used to return an error of ERRbadpath
445                                  * rather than ERRbadfile. Some Windows
446                                  * applications depend on the difference between
447                                  * these two errors.
448                                  */
449                                 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
450                                 goto fail;
451                         }
452
453                 } else {
454                         char *found_name = NULL;
455
456                         /* Stat failed - ensure we don't use it. */
457                         SET_STAT_INVALID(smb_fname->st);
458
459                         /*
460                          * Reset errno so we can detect
461                          * directory open errors.
462                          */
463                         errno = 0;
464
465                         /*
466                          * Try to find this part of the path in the directory.
467                          */
468
469                         if (name_has_wildcard ||
470                             (get_real_filename(conn, dirpath, start,
471                                                talloc_tos(),
472                                                &found_name) == -1)) {
473                                 char *unmangled;
474
475                                 if (end) {
476                                         /*
477                                          * An intermediate part of the name
478                                          * can't be found.
479                                          */
480                                         DEBUG(5,("Intermediate not found %s\n",
481                                                         start));
482                                         *end = '/';
483
484                                         /*
485                                          * We need to return the fact that the
486                                          * intermediate name resolution failed.
487                                          * This is used to return an error of
488                                          * ERRbadpath rather than ERRbadfile.
489                                          * Some Windows applications depend on
490                                          * the difference between these two
491                                          * errors.
492                                          */
493
494                                         /*
495                                          * ENOENT, ENOTDIR and ELOOP all map
496                                          * to NT_STATUS_OBJECT_PATH_NOT_FOUND
497                                          * in the filename walk.
498                                          */
499
500                                         if (errno == ENOENT ||
501                                                         errno == ENOTDIR ||
502                                                         errno == ELOOP) {
503                                                 status =
504                                                 NT_STATUS_OBJECT_PATH_NOT_FOUND;
505                                         }
506                                         else {
507                                                 status =
508                                                 map_nt_error_from_unix(errno);
509                                         }
510                                         goto fail;
511                                 }
512
513                                 /*
514                                  * ENOENT/EACCESS are the only valid errors
515                                  * here. EACCESS needs handling here for
516                                  * "dropboxes", i.e. directories where users
517                                  * can only put stuff with permission -wx.
518                                  */
519                                 if ((errno != 0) && (errno != ENOENT)
520                                     && (errno != EACCES)) {
521                                         /*
522                                          * ENOTDIR and ELOOP both map to
523                                          * NT_STATUS_OBJECT_PATH_NOT_FOUND
524                                          * in the filename walk.
525                                          */
526                                         if (errno == ENOTDIR ||
527                                                         errno == ELOOP) {
528                                                 status =
529                                                 NT_STATUS_OBJECT_PATH_NOT_FOUND;
530                                         } else {
531                                                 status =
532                                                 map_nt_error_from_unix(errno);
533                                         }
534                                         goto fail;
535                                 }
536
537                                 /*
538                                  * Just the last part of the name doesn't exist.
539                                  * We need to strupper() or strlower() it as
540                                  * this conversion may be used for file creation
541                                  * purposes. Fix inspired by
542                                  * Thomas Neumann <t.neumann@iku-ag.de>.
543                                  */
544                                 if (!conn->case_preserve ||
545                                     (mangle_is_8_3(start, False,
546                                                    conn->params) &&
547                                                  !conn->short_case_preserve)) {
548                                         strnorm(start,
549                                                 lp_defaultcase(SNUM(conn)));
550                                 }
551
552                                 /*
553                                  * check on the mangled stack to see if we can
554                                  * recover the base of the filename.
555                                  */
556
557                                 if (mangle_is_mangled(start, conn->params)
558                                     && mangle_lookup_name_from_8_3(ctx,
559                                                         start,
560                                                         &unmangled,
561                                                         conn->params)) {
562                                         char *tmp;
563                                         size_t start_ofs =
564                                             start - smb_fname->base_name;
565
566                                         if (*dirpath != '\0') {
567                                                 tmp = talloc_asprintf(
568                                                         smb_fname, "%s/%s",
569                                                         dirpath, unmangled);
570                                                 TALLOC_FREE(unmangled);
571                                         }
572                                         else {
573                                                 tmp = unmangled;
574                                         }
575                                         if (tmp == NULL) {
576                                                 DEBUG(0, ("talloc failed\n"));
577                                                 status = NT_STATUS_NO_MEMORY;
578                                                 goto err;
579                                         }
580                                         TALLOC_FREE(smb_fname->base_name);
581                                         smb_fname->base_name = tmp;
582                                         start =
583                                             smb_fname->base_name + start_ofs;
584                                         end = start + strlen(start);
585                                 }
586
587                                 DEBUG(5,("New file %s\n",start));
588                                 goto done;
589                         }
590
591
592                         /*
593                          * Restore the rest of the string. If the string was
594                          * mangled the size may have changed.
595                          */
596                         if (end) {
597                                 char *tmp;
598                                 size_t start_ofs =
599                                     start - smb_fname->base_name;
600
601                                 if (*dirpath != '\0') {
602                                         tmp = talloc_asprintf(smb_fname,
603                                                 "%s/%s/%s", dirpath,
604                                                 found_name, end+1);
605                                 }
606                                 else {
607                                         tmp = talloc_asprintf(smb_fname,
608                                                 "%s/%s", found_name,
609                                                 end+1);
610                                 }
611                                 if (tmp == NULL) {
612                                         DEBUG(0, ("talloc_asprintf failed\n"));
613                                         status = NT_STATUS_NO_MEMORY;
614                                         goto err;
615                                 }
616                                 TALLOC_FREE(smb_fname->base_name);
617                                 smb_fname->base_name = tmp;
618                                 start = smb_fname->base_name + start_ofs;
619                                 end = start + strlen(found_name);
620                                 *end = '\0';
621                         } else {
622                                 char *tmp;
623                                 size_t start_ofs =
624                                     start - smb_fname->base_name;
625
626                                 if (*dirpath != '\0') {
627                                         tmp = talloc_asprintf(smb_fname,
628                                                 "%s/%s", dirpath,
629                                                 found_name);
630                                 } else {
631                                         tmp = talloc_strdup(smb_fname,
632                                                 found_name);
633                                 }
634                                 if (tmp == NULL) {
635                                         DEBUG(0, ("talloc failed\n"));
636                                         status = NT_STATUS_NO_MEMORY;
637                                         goto err;
638                                 }
639                                 TALLOC_FREE(smb_fname->base_name);
640                                 smb_fname->base_name = tmp;
641                                 start = smb_fname->base_name + start_ofs;
642
643                                 /*
644                                  * We just scanned for, and found the end of
645                                  * the path. We must return a valid stat struct
646                                  * if it exists. JRA.
647                                  */
648
649                                 if (posix_pathnames) {
650                                         ret = SMB_VFS_LSTAT(conn, smb_fname);
651                                 } else {
652                                         ret = SMB_VFS_STAT(conn, smb_fname);
653                                 }
654
655                                 if (ret != 0) {
656                                         SET_STAT_INVALID(smb_fname->st);
657                                 }
658                         }
659
660                         TALLOC_FREE(found_name);
661                 } /* end else */
662
663 #ifdef DEVELOPER
664                 /*
665                  * This sucks!
666                  * We should never provide different behaviors
667                  * depending on DEVELOPER!!!
668                  */
669                 if (VALID_STAT(smb_fname->st)) {
670                         bool delete_pending;
671                         get_file_infos(vfs_file_id_from_sbuf(conn,
672                                                              &smb_fname->st),
673                                        &delete_pending, NULL);
674                         if (delete_pending) {
675                                 status = NT_STATUS_DELETE_PENDING;
676                                 goto fail;
677                         }
678                 }
679 #endif
680
681                 /*
682                  * Add to the dirpath that we have resolved so far.
683                  */
684
685                 if (*dirpath != '\0') {
686                         char *tmp = talloc_asprintf(ctx,
687                                         "%s/%s", dirpath, start);
688                         if (!tmp) {
689                                 DEBUG(0, ("talloc_asprintf failed\n"));
690                                 status = NT_STATUS_NO_MEMORY;
691                                 goto err;
692                         }
693                         TALLOC_FREE(dirpath);
694                         dirpath = tmp;
695                 }
696                 else {
697                         TALLOC_FREE(dirpath);
698                         if (!(dirpath = talloc_strdup(ctx,start))) {
699                                 DEBUG(0, ("talloc_strdup failed\n"));
700                                 status = NT_STATUS_NO_MEMORY;
701                                 goto err;
702                         }
703                 }
704
705                 /*
706                  * Cache the dirpath thus far. Don't cache a name with mangled
707                  * or wildcard components as this can change the size.
708                  */
709                 if(!component_was_mangled && !name_has_wildcard) {
710                         stat_cache_add(orig_path, dirpath,
711                                         conn->case_sensitive);
712                 }
713
714                 /*
715                  * Restore the / that we wiped out earlier.
716                  */
717                 if (end) {
718                         *end = '/';
719                 }
720         }
721
722         /*
723          * Cache the full path. Don't cache a name with mangled or wildcard
724          * components as this can change the size.
725          */
726
727         if(!component_was_mangled && !name_has_wildcard) {
728                 stat_cache_add(orig_path, smb_fname->base_name,
729                                conn->case_sensitive);
730         }
731
732         /*
733          * The name has been resolved.
734          */
735
736         DEBUG(5,("conversion finished %s -> %s\n", orig_path,
737                  smb_fname->base_name));
738
739  done:
740         /* Add back the stream if one was stripped off originally. */
741         if (stream != NULL) {
742                 smb_fname->stream_name = stream;
743
744                 /* Check path now that the base_name has been converted. */
745                 status = build_stream_path(ctx, conn, orig_path, smb_fname);
746                 if (!NT_STATUS_IS_OK(status)) {
747                         goto fail;
748                 }
749         }
750         TALLOC_FREE(dirpath);
751         *smb_fname_out = smb_fname;
752         return NT_STATUS_OK;
753  fail:
754         DEBUG(10, ("dirpath = [%s] start = [%s]\n", dirpath, start));
755         if (*dirpath != '\0') {
756                 smb_fname->base_name = talloc_asprintf(smb_fname, "%s/%s",
757                                                        dirpath, start);
758         } else {
759                 smb_fname->base_name = talloc_strdup(smb_fname, start);
760         }
761         if (!smb_fname->base_name) {
762                 DEBUG(0, ("talloc_asprintf failed\n"));
763                 status = NT_STATUS_NO_MEMORY;
764                 goto err;
765         }
766
767         *smb_fname_out = smb_fname;
768         TALLOC_FREE(dirpath);
769         return status;
770  err:
771         TALLOC_FREE(smb_fname);
772         return status;
773 }
774
775 /****************************************************************************
776  Check a filename - possibly calling check_reduced_name.
777  This is called by every routine before it allows an operation on a filename.
778  It does any final confirmation necessary to ensure that the filename is
779  a valid one for the user to access.
780 ****************************************************************************/
781
782 NTSTATUS check_name(connection_struct *conn, const char *name)
783 {
784         if (IS_VETO_PATH(conn, name))  {
785                 /* Is it not dot or dot dot. */
786                 if (!((name[0] == '.') && (!name[1] ||
787                                         (name[1] == '.' && !name[2])))) {
788                         DEBUG(5,("check_name: file path name %s vetoed\n",
789                                                 name));
790                         return map_nt_error_from_unix(ENOENT);
791                 }
792         }
793
794         if (!lp_widelinks(SNUM(conn)) || !lp_symlinks(SNUM(conn))) {
795                 NTSTATUS status = check_reduced_name(conn,name);
796                 if (!NT_STATUS_IS_OK(status)) {
797                         DEBUG(5,("check_name: name %s failed with %s\n",name,
798                                                 nt_errstr(status)));
799                         return status;
800                 }
801         }
802
803         return NT_STATUS_OK;
804 }
805
806 /****************************************************************************
807  Check if two filenames are equal.
808  This needs to be careful about whether we are case sensitive.
809 ****************************************************************************/
810
811 static bool fname_equal(const char *name1, const char *name2,
812                 bool case_sensitive)
813 {
814         /* Normal filename handling */
815         if (case_sensitive) {
816                 return(strcmp(name1,name2) == 0);
817         }
818
819         return(strequal(name1,name2));
820 }
821
822 /****************************************************************************
823  Scan a directory to find a filename, matching without case sensitivity.
824  If the name looks like a mangled name then try via the mangling functions
825 ****************************************************************************/
826
827 static int get_real_filename_full_scan(connection_struct *conn,
828                                        const char *path, const char *name,
829                                        bool mangled,
830                                        TALLOC_CTX *mem_ctx, char **found_name)
831 {
832         struct smb_Dir *cur_dir;
833         const char *dname = NULL;
834         char *talloced = NULL;
835         char *unmangled_name = NULL;
836         long curpos;
837
838         /* handle null paths */
839         if ((path == NULL) || (*path == 0)) {
840                 path = ".";
841         }
842
843         /* If we have a case-sensitive filesystem, it doesn't do us any
844          * good to search for a name. If a case variation of the name was
845          * there, then the original stat(2) would have found it.
846          */
847         if (!mangled && !(conn->fs_capabilities & FILE_CASE_SENSITIVE_SEARCH)) {
848                 errno = ENOENT;
849                 return -1;
850         }
851
852         /*
853          * The incoming name can be mangled, and if we de-mangle it
854          * here it will not compare correctly against the filename (name2)
855          * read from the directory and then mangled by the name_to_8_3()
856          * call. We need to mangle both names or neither.
857          * (JRA).
858          *
859          * Fix for bug found by Dina Fine. If in case sensitive mode then
860          * the mangle cache is no good (3 letter extension could be wrong
861          * case - so don't demangle in this case - leave as mangled and
862          * allow the mangling of the directory entry read (which is done
863          * case insensitively) to match instead. This will lead to more
864          * false positive matches but we fail completely without it. JRA.
865          */
866
867         if (mangled && !conn->case_sensitive) {
868                 mangled = !mangle_lookup_name_from_8_3(talloc_tos(), name,
869                                                        &unmangled_name,
870                                                        conn->params);
871                 if (!mangled) {
872                         /* Name is now unmangled. */
873                         name = unmangled_name;
874                 }
875         }
876
877         /* open the directory */
878         if (!(cur_dir = OpenDir(talloc_tos(), conn, path, NULL, 0))) {
879                 DEBUG(3,("scan dir didn't open dir [%s]\n",path));
880                 TALLOC_FREE(unmangled_name);
881                 return -1;
882         }
883
884         /* now scan for matching names */
885         curpos = 0;
886         while ((dname = ReadDirName(cur_dir, &curpos, NULL, &talloced))) {
887
888                 /* Is it dot or dot dot. */
889                 if (ISDOT(dname) || ISDOTDOT(dname)) {
890                         TALLOC_FREE(talloced);
891                         continue;
892                 }
893
894                 /*
895                  * At this point dname is the unmangled name.
896                  * name is either mangled or not, depending on the state
897                  * of the "mangled" variable. JRA.
898                  */
899
900                 /*
901                  * Check mangled name against mangled name, or unmangled name
902                  * against unmangled name.
903                  */
904
905                 if ((mangled && mangled_equal(name,dname,conn->params)) ||
906                         fname_equal(name, dname, conn->case_sensitive)) {
907                         /* we've found the file, change it's name and return */
908                         *found_name = talloc_strdup(mem_ctx, dname);
909                         TALLOC_FREE(unmangled_name);
910                         TALLOC_FREE(cur_dir);
911                         if (!*found_name) {
912                                 errno = ENOMEM;
913                                 TALLOC_FREE(talloced);
914                                 return -1;
915                         }
916                         TALLOC_FREE(talloced);
917                         return 0;
918                 }
919                 TALLOC_FREE(talloced);
920         }
921
922         TALLOC_FREE(unmangled_name);
923         TALLOC_FREE(cur_dir);
924         errno = ENOENT;
925         return -1;
926 }
927
928 /****************************************************************************
929  Wrapper around the vfs get_real_filename and the full directory scan
930  fallback.
931 ****************************************************************************/
932
933 int get_real_filename(connection_struct *conn, const char *path,
934                       const char *name, TALLOC_CTX *mem_ctx,
935                       char **found_name)
936 {
937         int ret;
938         bool mangled;
939
940         mangled = mangle_is_mangled(name, conn->params);
941
942         if (mangled) {
943                 return get_real_filename_full_scan(conn, path, name, mangled,
944                                                    mem_ctx, found_name);
945         }
946
947         /* Try the vfs first to take advantage of case-insensitive stat. */
948         ret = SMB_VFS_GET_REAL_FILENAME(conn, path, name, mem_ctx, found_name);
949
950         /*
951          * If the case-insensitive stat was successful, or returned an error
952          * other than EOPNOTSUPP then there is no need to fall back on the
953          * full directory scan.
954          */
955         if (ret == 0 || (ret == -1 && errno != EOPNOTSUPP)) {
956                 return ret;
957         }
958
959         return get_real_filename_full_scan(conn, path, name, mangled, mem_ctx,
960                                            found_name);
961 }
962
963 static NTSTATUS build_stream_path(TALLOC_CTX *mem_ctx,
964                                   connection_struct *conn,
965                                   const char *orig_path,
966                                   struct smb_filename *smb_fname)
967 {
968         NTSTATUS status;
969         unsigned int i, num_streams;
970         struct stream_struct *streams = NULL;
971
972         if (SMB_VFS_STAT(conn, smb_fname) == 0) {
973                 DEBUG(10, ("'%s' exists\n", smb_fname_str_dbg(smb_fname)));
974                 return NT_STATUS_OK;
975         }
976
977         if (errno != ENOENT) {
978                 DEBUG(10, ("vfs_stat failed: %s\n", strerror(errno)));
979                 status = map_nt_error_from_unix(errno);
980                 goto fail;
981         }
982
983         /* Fall back to a case-insensitive scan of all streams on the file. */
984         status = SMB_VFS_STREAMINFO(conn, NULL, smb_fname->base_name, mem_ctx,
985                                     &num_streams, &streams);
986
987         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
988                 SET_STAT_INVALID(smb_fname->st);
989                 return NT_STATUS_OK;
990         }
991
992         if (!NT_STATUS_IS_OK(status)) {
993                 DEBUG(10, ("vfs_streaminfo failed: %s\n", nt_errstr(status)));
994                 goto fail;
995         }
996
997         for (i=0; i<num_streams; i++) {
998                 DEBUG(10, ("comparing [%s] and [%s]: ",
999                            smb_fname->stream_name, streams[i].name));
1000                 if (fname_equal(smb_fname->stream_name, streams[i].name,
1001                                 conn->case_sensitive)) {
1002                         DEBUGADD(10, ("equal\n"));
1003                         break;
1004                 }
1005                 DEBUGADD(10, ("not equal\n"));
1006         }
1007
1008         /* Couldn't find the stream. */
1009         if (i == num_streams) {
1010                 SET_STAT_INVALID(smb_fname->st);
1011                 TALLOC_FREE(streams);
1012                 return NT_STATUS_OK;
1013         }
1014
1015         DEBUG(10, ("case insensitive stream. requested: %s, actual: %s\n",
1016                 smb_fname->stream_name, streams[i].name));
1017
1018
1019         TALLOC_FREE(smb_fname->stream_name);
1020         smb_fname->stream_name = talloc_strdup(smb_fname, streams[i].name);
1021         if (smb_fname->stream_name == NULL) {
1022                 status = NT_STATUS_NO_MEMORY;
1023                 goto fail;
1024         }
1025
1026         SET_STAT_INVALID(smb_fname->st);
1027
1028         if (SMB_VFS_STAT(conn, smb_fname) == 0) {
1029                 DEBUG(10, ("'%s' exists\n", smb_fname_str_dbg(smb_fname)));
1030         }
1031         status = NT_STATUS_OK;
1032  fail:
1033         TALLOC_FREE(streams);
1034         return status;
1035 }
1036
1037 /**
1038  * Go through all the steps to validate a filename.
1039  *
1040  * @param ctx           talloc_ctx to allocate memory with.
1041  * @param conn          connection struct for vfs calls.
1042  * @param dfs_path      Whether this path requires dfs resolution.
1043  * @param name_in       The unconverted name.
1044  * @param ucf_flags     flags to pass through to unix_convert().
1045  *                      UCF_ALWAYS_ALLOW_WCARD_LCOMP will be OR'd in if
1046  *                      p_cont_wcard != NULL and is true and
1047  *                      UCF_COND_ALLOW_WCARD_LCOMP.
1048  * @param p_cont_wcard  If not NULL, will be set to true if the dfs path
1049  *                      resolution detects a wildcard.
1050  * @param pp_smb_fname  The final converted name will be allocated if the
1051  *                      return is NT_STATUS_OK.
1052  *
1053  * @return NT_STATUS_OK if all operations completed succesfully, appropriate
1054  *         error otherwise.
1055  */
1056 NTSTATUS filename_convert(TALLOC_CTX *ctx,
1057                                 connection_struct *conn,
1058                                 bool dfs_path,
1059                                 const char *name_in,
1060                                 uint32_t ucf_flags,
1061                                 bool *ppath_contains_wcard,
1062                                 struct smb_filename **pp_smb_fname)
1063 {
1064         NTSTATUS status;
1065         char *fname = NULL;
1066
1067         *pp_smb_fname = NULL;
1068
1069         status = resolve_dfspath_wcard(ctx, conn,
1070                                 dfs_path,
1071                                 name_in,
1072                                 &fname,
1073                                 ppath_contains_wcard);
1074         if (!NT_STATUS_IS_OK(status)) {
1075                 DEBUG(10,("filename_convert: resolve_dfspath failed "
1076                         "for name %s with %s\n",
1077                         name_in,
1078                         nt_errstr(status) ));
1079                 return status;
1080         }
1081
1082         if (is_fake_file_path(name_in)) {
1083                 SMB_STRUCT_STAT st;
1084                 ZERO_STRUCT(st);
1085                 st.st_ex_nlink = 1;
1086                 status = create_synthetic_smb_fname_split(ctx,
1087                                                           name_in,
1088                                                           &st,
1089                                                           pp_smb_fname);
1090                 return status;
1091         }
1092
1093         /*
1094          * If the caller conditionally allows wildcard lookups, only add the
1095          * always allow if the path actually does contain a wildcard.
1096          */
1097         if (ucf_flags & UCF_COND_ALLOW_WCARD_LCOMP &&
1098             ppath_contains_wcard != NULL && *ppath_contains_wcard) {
1099                 ucf_flags |= UCF_ALWAYS_ALLOW_WCARD_LCOMP;
1100         }
1101
1102         status = unix_convert(ctx, conn, fname, pp_smb_fname, ucf_flags);
1103         if (!NT_STATUS_IS_OK(status)) {
1104                 DEBUG(10,("filename_convert: unix_convert failed "
1105                         "for name %s with %s\n",
1106                         fname,
1107                         nt_errstr(status) ));
1108                 return status;
1109         }
1110
1111         status = check_name(conn, (*pp_smb_fname)->base_name);
1112         if (!NT_STATUS_IS_OK(status)) {
1113                 DEBUG(3,("filename_convert: check_name failed "
1114                         "for name %s with %s\n",
1115                         smb_fname_str_dbg(*pp_smb_fname),
1116                         nt_errstr(status) ));
1117                 TALLOC_FREE(*pp_smb_fname);
1118                 return status;
1119         }
1120
1121         return status;
1122 }