s4:installmisc - install also the new "domainlevel" tool from the setup dir
[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                         conn->case_sensitive) {
796                 NTSTATUS status = check_reduced_name(conn,name);
797                 if (!NT_STATUS_IS_OK(status)) {
798                         DEBUG(5,("check_name: name %s failed with %s\n",name,
799                                                 nt_errstr(status)));
800                         return status;
801                 }
802         }
803
804         return NT_STATUS_OK;
805 }
806
807 /****************************************************************************
808  Check if two filenames are equal.
809  This needs to be careful about whether we are case sensitive.
810 ****************************************************************************/
811
812 static bool fname_equal(const char *name1, const char *name2,
813                 bool case_sensitive)
814 {
815         /* Normal filename handling */
816         if (case_sensitive) {
817                 return(strcmp(name1,name2) == 0);
818         }
819
820         return(strequal(name1,name2));
821 }
822
823 /****************************************************************************
824  Scan a directory to find a filename, matching without case sensitivity.
825  If the name looks like a mangled name then try via the mangling functions
826 ****************************************************************************/
827
828 static int get_real_filename_full_scan(connection_struct *conn,
829                                        const char *path, const char *name,
830                                        bool mangled,
831                                        TALLOC_CTX *mem_ctx, char **found_name)
832 {
833         struct smb_Dir *cur_dir;
834         const char *dname = NULL;
835         char *talloced = NULL;
836         char *unmangled_name = NULL;
837         long curpos;
838
839         /* handle null paths */
840         if ((path == NULL) || (*path == 0)) {
841                 path = ".";
842         }
843
844         /* If we have a case-sensitive filesystem, it doesn't do us any
845          * good to search for a name. If a case variation of the name was
846          * there, then the original stat(2) would have found it.
847          */
848         if (!mangled && !(conn->fs_capabilities & FILE_CASE_SENSITIVE_SEARCH)) {
849                 errno = ENOENT;
850                 return -1;
851         }
852
853         /*
854          * The incoming name can be mangled, and if we de-mangle it
855          * here it will not compare correctly against the filename (name2)
856          * read from the directory and then mangled by the name_to_8_3()
857          * call. We need to mangle both names or neither.
858          * (JRA).
859          *
860          * Fix for bug found by Dina Fine. If in case sensitive mode then
861          * the mangle cache is no good (3 letter extension could be wrong
862          * case - so don't demangle in this case - leave as mangled and
863          * allow the mangling of the directory entry read (which is done
864          * case insensitively) to match instead. This will lead to more
865          * false positive matches but we fail completely without it. JRA.
866          */
867
868         if (mangled && !conn->case_sensitive) {
869                 mangled = !mangle_lookup_name_from_8_3(talloc_tos(), name,
870                                                        &unmangled_name,
871                                                        conn->params);
872                 if (!mangled) {
873                         /* Name is now unmangled. */
874                         name = unmangled_name;
875                 }
876         }
877
878         /* open the directory */
879         if (!(cur_dir = OpenDir(talloc_tos(), conn, path, NULL, 0))) {
880                 DEBUG(3,("scan dir didn't open dir [%s]\n",path));
881                 TALLOC_FREE(unmangled_name);
882                 return -1;
883         }
884
885         /* now scan for matching names */
886         curpos = 0;
887         while ((dname = ReadDirName(cur_dir, &curpos, NULL, &talloced))) {
888
889                 /* Is it dot or dot dot. */
890                 if (ISDOT(dname) || ISDOTDOT(dname)) {
891                         TALLOC_FREE(talloced);
892                         continue;
893                 }
894
895                 /*
896                  * At this point dname is the unmangled name.
897                  * name is either mangled or not, depending on the state
898                  * of the "mangled" variable. JRA.
899                  */
900
901                 /*
902                  * Check mangled name against mangled name, or unmangled name
903                  * against unmangled name.
904                  */
905
906                 if ((mangled && mangled_equal(name,dname,conn->params)) ||
907                         fname_equal(name, dname, conn->case_sensitive)) {
908                         /* we've found the file, change it's name and return */
909                         *found_name = talloc_strdup(mem_ctx, dname);
910                         TALLOC_FREE(unmangled_name);
911                         TALLOC_FREE(cur_dir);
912                         if (!*found_name) {
913                                 errno = ENOMEM;
914                                 TALLOC_FREE(talloced);
915                                 return -1;
916                         }
917                         TALLOC_FREE(talloced);
918                         return 0;
919                 }
920                 TALLOC_FREE(talloced);
921         }
922
923         TALLOC_FREE(unmangled_name);
924         TALLOC_FREE(cur_dir);
925         errno = ENOENT;
926         return -1;
927 }
928
929 /****************************************************************************
930  Wrapper around the vfs get_real_filename and the full directory scan
931  fallback.
932 ****************************************************************************/
933
934 int get_real_filename(connection_struct *conn, const char *path,
935                       const char *name, TALLOC_CTX *mem_ctx,
936                       char **found_name)
937 {
938         int ret;
939         bool mangled;
940
941         mangled = mangle_is_mangled(name, conn->params);
942
943         if (mangled) {
944                 return get_real_filename_full_scan(conn, path, name, mangled,
945                                                    mem_ctx, found_name);
946         }
947
948         /* Try the vfs first to take advantage of case-insensitive stat. */
949         ret = SMB_VFS_GET_REAL_FILENAME(conn, path, name, mem_ctx, found_name);
950
951         /*
952          * If the case-insensitive stat was successful, or returned an error
953          * other than EOPNOTSUPP then there is no need to fall back on the
954          * full directory scan.
955          */
956         if (ret == 0 || (ret == -1 && errno != EOPNOTSUPP)) {
957                 return ret;
958         }
959
960         return get_real_filename_full_scan(conn, path, name, mangled, mem_ctx,
961                                            found_name);
962 }
963
964 static NTSTATUS build_stream_path(TALLOC_CTX *mem_ctx,
965                                   connection_struct *conn,
966                                   const char *orig_path,
967                                   struct smb_filename *smb_fname)
968 {
969         NTSTATUS status;
970         unsigned int i, num_streams;
971         struct stream_struct *streams = NULL;
972
973         if (SMB_VFS_STAT(conn, smb_fname) == 0) {
974                 DEBUG(10, ("'%s' exists\n", smb_fname_str_dbg(smb_fname)));
975                 return NT_STATUS_OK;
976         }
977
978         if (errno != ENOENT) {
979                 DEBUG(10, ("vfs_stat failed: %s\n", strerror(errno)));
980                 status = map_nt_error_from_unix(errno);
981                 goto fail;
982         }
983
984         /* Fall back to a case-insensitive scan of all streams on the file. */
985         status = SMB_VFS_STREAMINFO(conn, NULL, smb_fname->base_name, mem_ctx,
986                                     &num_streams, &streams);
987
988         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
989                 SET_STAT_INVALID(smb_fname->st);
990                 return NT_STATUS_OK;
991         }
992
993         if (!NT_STATUS_IS_OK(status)) {
994                 DEBUG(10, ("vfs_streaminfo failed: %s\n", nt_errstr(status)));
995                 goto fail;
996         }
997
998         for (i=0; i<num_streams; i++) {
999                 DEBUG(10, ("comparing [%s] and [%s]: ",
1000                            smb_fname->stream_name, streams[i].name));
1001                 if (fname_equal(smb_fname->stream_name, streams[i].name,
1002                                 conn->case_sensitive)) {
1003                         DEBUGADD(10, ("equal\n"));
1004                         break;
1005                 }
1006                 DEBUGADD(10, ("not equal\n"));
1007         }
1008
1009         /* Couldn't find the stream. */
1010         if (i == num_streams) {
1011                 SET_STAT_INVALID(smb_fname->st);
1012                 TALLOC_FREE(streams);
1013                 return NT_STATUS_OK;
1014         }
1015
1016         DEBUG(10, ("case insensitive stream. requested: %s, actual: %s\n",
1017                 smb_fname->stream_name, streams[i].name));
1018
1019
1020         TALLOC_FREE(smb_fname->stream_name);
1021         smb_fname->stream_name = talloc_strdup(smb_fname, streams[i].name);
1022         if (smb_fname->stream_name == NULL) {
1023                 status = NT_STATUS_NO_MEMORY;
1024                 goto fail;
1025         }
1026
1027         SET_STAT_INVALID(smb_fname->st);
1028
1029         if (SMB_VFS_STAT(conn, smb_fname) == 0) {
1030                 DEBUG(10, ("'%s' exists\n", smb_fname_str_dbg(smb_fname)));
1031         }
1032         status = NT_STATUS_OK;
1033  fail:
1034         TALLOC_FREE(streams);
1035         return status;
1036 }
1037
1038 /**
1039  * Go through all the steps to validate a filename.
1040  *
1041  * @param ctx           talloc_ctx to allocate memory with.
1042  * @param conn          connection struct for vfs calls.
1043  * @param dfs_path      Whether this path requires dfs resolution.
1044  * @param name_in       The unconverted name.
1045  * @param ucf_flags     flags to pass through to unix_convert().
1046  *                      UCF_ALWAYS_ALLOW_WCARD_LCOMP will be OR'd in if
1047  *                      p_cont_wcard != NULL and is true and
1048  *                      UCF_COND_ALLOW_WCARD_LCOMP.
1049  * @param p_cont_wcard  If not NULL, will be set to true if the dfs path
1050  *                      resolution detects a wildcard.
1051  * @param pp_smb_fname  The final converted name will be allocated if the
1052  *                      return is NT_STATUS_OK.
1053  *
1054  * @return NT_STATUS_OK if all operations completed succesfully, appropriate
1055  *         error otherwise.
1056  */
1057 NTSTATUS filename_convert(TALLOC_CTX *ctx,
1058                                 connection_struct *conn,
1059                                 bool dfs_path,
1060                                 const char *name_in,
1061                                 uint32_t ucf_flags,
1062                                 bool *ppath_contains_wcard,
1063                                 struct smb_filename **pp_smb_fname)
1064 {
1065         NTSTATUS status;
1066         char *fname = NULL;
1067
1068         *pp_smb_fname = NULL;
1069
1070         status = resolve_dfspath_wcard(ctx, conn,
1071                                 dfs_path,
1072                                 name_in,
1073                                 &fname,
1074                                 ppath_contains_wcard);
1075         if (!NT_STATUS_IS_OK(status)) {
1076                 DEBUG(10,("filename_convert: resolve_dfspath failed "
1077                         "for name %s with %s\n",
1078                         name_in,
1079                         nt_errstr(status) ));
1080                 return status;
1081         }
1082
1083         if (is_fake_file_path(name_in)) {
1084                 SMB_STRUCT_STAT st;
1085                 ZERO_STRUCT(st);
1086                 st.st_ex_nlink = 1;
1087                 status = create_synthetic_smb_fname_split(ctx,
1088                                                           name_in,
1089                                                           &st,
1090                                                           pp_smb_fname);
1091                 return status;
1092         }
1093
1094         /*
1095          * If the caller conditionally allows wildcard lookups, only add the
1096          * always allow if the path actually does contain a wildcard.
1097          */
1098         if (ucf_flags & UCF_COND_ALLOW_WCARD_LCOMP &&
1099             ppath_contains_wcard != NULL && *ppath_contains_wcard) {
1100                 ucf_flags |= UCF_ALWAYS_ALLOW_WCARD_LCOMP;
1101         }
1102
1103         status = unix_convert(ctx, conn, fname, pp_smb_fname, ucf_flags);
1104         if (!NT_STATUS_IS_OK(status)) {
1105                 DEBUG(10,("filename_convert: unix_convert failed "
1106                         "for name %s with %s\n",
1107                         fname,
1108                         nt_errstr(status) ));
1109                 return status;
1110         }
1111
1112         status = check_name(conn, (*pp_smb_fname)->base_name);
1113         if (!NT_STATUS_IS_OK(status)) {
1114                 DEBUG(3,("filename_convert: check_name failed "
1115                         "for name %s with %s\n",
1116                         smb_fname_str_dbg(*pp_smb_fname),
1117                         nt_errstr(status) ));
1118                 TALLOC_FREE(*pp_smb_fname);
1119                 return status;
1120         }
1121
1122         return status;
1123 }