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