fixed a stat cache bug (the one found by Matthew Geier).
[tprouty/samba.git] / source3 / smbd / filename.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    filename handling routines
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 extern int DEBUGLEVEL;
25 extern BOOL case_sensitive;
26 extern BOOL case_preserve;
27 extern BOOL short_case_preserve;
28 extern fstring remote_machine;
29 extern BOOL use_mangled_map;
30
31 static BOOL scan_directory(char *path, char *name,connection_struct *conn,BOOL docache);
32
33 /****************************************************************************
34  Check if two filenames are equal.
35  This needs to be careful about whether we are case sensitive.
36 ****************************************************************************/
37 static BOOL fname_equal(char *name1, char *name2)
38 {
39   int l1 = strlen(name1);
40   int l2 = strlen(name2);
41
42   /* handle filenames ending in a single dot */
43   if (l1-l2 == 1 && name1[l1-1] == '.' && lp_strip_dot())
44     {
45       BOOL ret;
46       name1[l1-1] = 0;
47       ret = fname_equal(name1,name2);
48       name1[l1-1] = '.';
49       return(ret);
50     }
51
52   if (l2-l1 == 1 && name2[l2-1] == '.' && lp_strip_dot())
53     {
54       BOOL ret;
55       name2[l2-1] = 0;
56       ret = fname_equal(name1,name2);
57       name2[l2-1] = '.';
58       return(ret);
59     }
60
61   /* now normal filename handling */
62   if (case_sensitive)
63     return(strcmp(name1,name2) == 0);
64
65   return(strequal(name1,name2));
66 }
67
68
69 /****************************************************************************
70  Mangle the 2nd name and check if it is then equal to the first name.
71 ****************************************************************************/
72 static BOOL mangled_equal(char *name1, char *name2)
73 {
74   pstring tmpname;
75
76   if (is_8_3(name2, True))
77     return(False);
78
79   pstrcpy(tmpname,name2);
80   mangle_name_83(tmpname);
81
82   return(strequal(name1,tmpname));
83 }
84
85 /****************************************************************************
86  Stat cache code used in unix_convert.
87 *****************************************************************************/
88
89 static int global_stat_cache_lookups;
90 static int global_stat_cache_misses;
91 static int global_stat_cache_hits;
92
93 /****************************************************************************
94  Stat cache statistics code.
95 *****************************************************************************/
96
97 void print_stat_cache_statistics(void)
98 {
99   double eff = (100.0* (double)global_stat_cache_hits)/(double)global_stat_cache_lookups;
100
101   DEBUG(0,("stat cache stats: lookups = %d, hits = %d, misses = %d, \
102 stat cache was %f%% effective.\n", global_stat_cache_lookups,
103        global_stat_cache_hits, global_stat_cache_misses, eff ));
104 }
105
106 typedef struct {
107   ubi_dlNode link;
108   int name_len;
109   pstring orig_name;
110   pstring translated_name;
111 } stat_cache_entry;
112
113 #define MAX_STAT_CACHE_SIZE 50
114
115 static ubi_dlList stat_cache = { NULL, (ubi_dlNodePtr)&stat_cache, 0};
116
117 /****************************************************************************
118  Compare two names in the stat cache - to check if we already have such an
119  entry.
120 *****************************************************************************/
121
122 static BOOL stat_name_equal( char *s1, char *s2)
123 {
124   return (case_sensitive ? (strcmp( s1, s2) == 0) : (StrCaseCmp(s1, s2) == 0));
125 }
126
127 /****************************************************************************
128  Compare a pathname to a name in the stat cache - of a given length.
129  Note - this code always checks that the next character in the pathname
130  is either a '/' character, or a '\0' character - to ensure we only
131  match *full* pathname components.
132 *****************************************************************************/
133
134 static BOOL stat_name_equal_len( char *stat_name, char *orig_name, int len)
135 {
136   BOOL matched = (case_sensitive ? (strncmp( stat_name, orig_name, len) == 0) :
137                            (StrnCaseCmp(stat_name, orig_name, len) == 0));
138   if(orig_name[len] != '/' && orig_name[len] != '\0')
139     return False;
140
141   return matched;
142 }
143
144 /****************************************************************************
145  Add an entry into the stat cache.
146 *****************************************************************************/
147
148 static void stat_cache_add( char *full_orig_name, char *orig_translated_path)
149 {
150   stat_cache_entry *scp;
151   pstring orig_name;
152   pstring translated_path;
153   int namelen = strlen(orig_translated_path);
154
155   /*
156    * Don't cache trivial valid directory entries.
157    */
158   if(strequal(full_orig_name, ".") || strequal(full_orig_name, ".."))
159     return;
160
161   /*
162    * If we are in case insentive mode, we need to
163    * store names that need no translation - else, it
164    * would be a waste.
165    */
166
167   if(case_sensitive && (strcmp(full_orig_name, orig_translated_path) == 0))
168     return;
169
170   /*
171    * Remove any trailing '/' characters from the
172    * translated path.
173    */
174
175   pstrcpy(translated_path, orig_translated_path);
176   if(translated_path[namelen-1] == '/') {
177     translated_path[namelen-1] = '\0';
178     namelen--;
179   }
180
181   /*
182    * We will only replace namelen characters 
183    * of full_orig_name.
184    * StrnCpy always null terminates.
185    */
186
187   StrnCpy(orig_name, full_orig_name, namelen);
188
189   /*
190    * Check this name doesn't exist in the cache before we 
191    * add it.
192    */
193
194   for( scp = (stat_cache_entry *)ubi_dlFirst( &stat_cache); scp; 
195                         scp = (stat_cache_entry *)ubi_dlNext( scp )) {
196     if(stat_name_equal( scp->orig_name, orig_name) &&
197        (strcmp( scp->translated_name, translated_path) == 0)) {
198       /*
199        * Name does exist - promote it.
200        */
201       if( (stat_cache_entry *)ubi_dlFirst( &stat_cache) != scp ) {
202         ubi_dlRemThis( &stat_cache, scp);
203         ubi_dlAddHead( &stat_cache, scp);
204       }
205       return;
206     }
207   }
208
209   if((scp = (stat_cache_entry *)malloc(sizeof(stat_cache_entry))) == NULL) {
210     DEBUG(0,("stat_cache_add: Out of memory !\n"));
211     return;
212   }
213
214   pstrcpy(scp->orig_name, orig_name);
215   pstrcpy(scp->translated_name, translated_path);
216   scp->name_len = namelen;
217
218   ubi_dlAddHead( &stat_cache, scp);
219
220   DEBUG(10,("stat_cache_add: Added entry %s -> %s\n", scp->orig_name, scp->translated_name ));
221
222   if(ubi_dlCount(&stat_cache) > lp_stat_cache_size()) {
223     scp = (stat_cache_entry *)ubi_dlRemTail( &stat_cache );
224     free((char *)scp);
225     return;
226   }
227 }
228
229 /****************************************************************************
230  Look through the stat cache for an entry - promote it to the top if found.
231  Return True if we translated (and did a scuccessful stat on) the entire name.
232 *****************************************************************************/
233
234 static BOOL stat_cache_lookup( char *name, char *dirpath, char **start, SMB_STRUCT_STAT *pst)
235 {
236   stat_cache_entry *scp;
237   stat_cache_entry *longest_hit = NULL;
238   int namelen = strlen(name);
239  
240   *start = name;
241   global_stat_cache_lookups++;
242
243   /*
244    * Don't lookup trivial valid directory entries.
245    */
246   if(strequal(name, ".") || strequal(name, "..")) {
247     global_stat_cache_misses++;
248     return False;
249   }
250
251   for( scp = (stat_cache_entry *)ubi_dlFirst( &stat_cache); scp; 
252                         scp = (stat_cache_entry *)ubi_dlNext( scp )) {
253     if(scp->name_len <= namelen) {
254       if(stat_name_equal_len(scp->orig_name, name, scp->name_len)) {
255         if((longest_hit == NULL) || (longest_hit->name_len <= scp->name_len))
256           longest_hit = scp;
257       }
258     }
259   }
260
261   if(longest_hit == NULL) {
262     DEBUG(10,("stat_cache_lookup: cache miss on %s\n", name));
263     global_stat_cache_misses++;
264     return False;
265   }
266
267   global_stat_cache_hits++;
268
269   DEBUG(10,("stat_cache_lookup: cache hit for name %s. %s -> %s\n",
270         name, longest_hit->orig_name, longest_hit->translated_name ));
271
272   /*
273    * longest_hit is the longest match we got in the list.
274    * Check it exists - if so, overwrite the original name
275    * and then promote it to the top.
276    */
277
278   if(dos_stat( longest_hit->translated_name, pst) != 0) {
279     /*
280      * Discard this entry.
281      */
282     ubi_dlRemThis( &stat_cache, longest_hit);
283     free((char *)longest_hit);
284     return False;
285   }
286
287   memcpy(name, longest_hit->translated_name, longest_hit->name_len);
288   if( (stat_cache_entry *)ubi_dlFirst( &stat_cache) != longest_hit ) {
289     ubi_dlRemThis( &stat_cache, longest_hit);
290     ubi_dlAddHead( &stat_cache, longest_hit);
291   }
292
293   *start = &name[longest_hit->name_len];
294   if(**start == '/')
295     ++*start;
296
297   StrnCpy( dirpath, longest_hit->translated_name, name - (*start));
298
299   return (namelen == longest_hit->name_len);
300 }
301
302 /****************************************************************************
303 This routine is called to convert names from the dos namespace to unix
304 namespace. It needs to handle any case conversions, mangling, format
305 changes etc.
306
307 We assume that we have already done a chdir() to the right "root" directory
308 for this service.
309
310 The function will return False if some part of the name except for the last
311 part cannot be resolved
312
313 If the saved_last_component != 0, then the unmodified last component
314 of the pathname is returned there. This is used in an exceptional
315 case in reply_mv (so far). If saved_last_component == 0 then nothing
316 is returned there.
317
318 The bad_path arg is set to True if the filename walk failed. This is
319 used to pick the correct error code to return between ENOENT and ENOTDIR
320 as Windows applications depend on ERRbadpath being returned if a component
321 of a pathname does not exist.
322 ****************************************************************************/
323
324 BOOL unix_convert(char *name,connection_struct *conn,char *saved_last_component, 
325                   BOOL *bad_path, SMB_STRUCT_STAT *pst)
326 {
327   SMB_STRUCT_STAT st;
328   char *start, *end, *orig_start;
329   pstring dirpath;
330   pstring orig_path;
331   int saved_errno;
332   BOOL component_was_mangled = False;
333   BOOL name_has_wildcard = False;
334   extern char magic_char;
335
336   *dirpath = 0;
337   *bad_path = False;
338   if(pst) {
339           ZERO_STRUCTP(pst);
340   }
341
342   if(saved_last_component)
343     *saved_last_component = 0;
344
345   /* 
346    * Convert to basic unix format - removing \ chars and cleaning it up.
347    */
348
349   unix_format(name);
350   unix_clean_name(name);
351
352   /* 
353    * Names must be relative to the root of the service - trim any leading /.
354    * also trim trailing /'s.
355    */
356
357   trim_string(name,"/","/");
358
359   /*
360    * Ensure saved_last_component is valid even if file exists.
361    */
362
363   if(saved_last_component) {
364     end = strrchr(name, '/');
365     if(end)
366       pstrcpy(saved_last_component, end + 1);
367     else
368       pstrcpy(saved_last_component, name);
369   }
370
371   if (!case_sensitive && 
372       (!case_preserve || (is_8_3(name, False) && !short_case_preserve)))
373     strnorm(name);
374
375   /* 
376    * Check if it's a printer file.
377    */
378   if (conn->printer) {
379     if ((! *name) || strchr(name,'/') || !is_8_3(name, True)) {
380       char *s;
381       fstring name2;
382       slprintf(name2,sizeof(name2)-1,"%.6s.XXXXXX",remote_machine);
383
384       /* 
385        * Sanitise the name.
386        */
387
388       for (s=name2 ; *s ; s++)
389         if (!issafe(*s)) *s = '_';
390           pstrcpy(name,(char *)mktemp(name2));    
391     }      
392     return(True);
393   }
394
395   start = name;
396   while (strncmp(start,"./",2) == 0)
397     start += 2;
398
399   pstrcpy(orig_path, name);
400
401   if(stat_cache_lookup( name, dirpath, &start, &st)) {
402     if(pst)
403       *pst = st;
404     return True;
405   }
406
407   /* 
408    * stat the name - if it exists then we are all done!
409    */
410
411   if (dos_stat(name,&st) == 0) {
412     stat_cache_add(orig_path, name);
413     DEBUG(5,("conversion finished %s -> %s\n",orig_path, name));
414     if(pst)
415       *pst = st;
416     return(True);
417   }
418
419   saved_errno = errno;
420
421   DEBUG(5,("unix_convert begin: name = %s, dirpath = %s, start = %s\n",
422         name, dirpath, start));
423
424   /* 
425    * A special case - if we don't have any mangling chars and are case
426    * sensitive then searching won't help.
427    */
428
429   if (case_sensitive && !is_mangled(name) && 
430       !lp_strip_dot() && !use_mangled_map && (saved_errno != ENOENT))
431     return(False);
432
433   if(strchr(start,'?') || strchr(start,'*'))
434     name_has_wildcard = True;
435
436   /* this is an extremely conservative test for mangled names. */
437   if (strchr(start,magic_char))
438     component_was_mangled = True;
439
440   /* 
441    * Now we need to recursively match the name against the real 
442    * directory structure.
443    */
444
445   /* 
446    * Match each part of the path name separately, trying the names
447    * as is first, then trying to scan the directory for matching names.
448    */
449
450   for (orig_start = start; start ; start = (end?end+1:(char *)NULL)) {
451       /* 
452        * Pinpoint the end of this section of the filename.
453        */
454       end = strchr(start, '/');
455
456       /* 
457        * Chop the name at this point.
458        */
459       if (end) 
460         *end = 0;
461
462       if(saved_last_component != 0)
463         pstrcpy(saved_last_component, end ? end + 1 : start);
464
465       /* 
466        * Check if the name exists up to this point.
467        */
468       if (dos_stat(name, &st) == 0) {
469         /*
470          * It exists. it must either be a directory or this must be
471          * the last part of the path for it to be OK.
472          */
473         if (end && !(st.st_mode & S_IFDIR)) {
474           /*
475            * An intermediate part of the name isn't a directory.
476             */
477           DEBUG(5,("Not a dir %s\n",start));
478           *end = '/';
479           return(False);
480         }
481
482       } else {
483         pstring rest;
484
485         *rest = 0;
486
487         /*
488          * Remember the rest of the pathname so it can be restored
489          * later.
490          */
491
492         if (end)
493           pstrcpy(rest,end+1);
494
495         /*
496          * Try to find this part of the path in the directory.
497          */
498
499         if (strchr(start,'?') || strchr(start,'*') ||
500             !scan_directory(dirpath, start, conn, end?True:False)) {
501           if (end) {
502             /*
503              * An intermediate part of the name can't be found.
504              */
505             DEBUG(5,("Intermediate not found %s\n",start));
506             *end = '/';
507
508             /* 
509              * We need to return the fact that the intermediate
510              * name resolution failed. This is used to return an
511              * error of ERRbadpath rather than ERRbadfile. Some
512              * Windows applications depend on the difference between
513              * these two errors.
514              */
515             *bad_path = True;
516             return(False);
517           }
518               
519           /* 
520            * Just the last part of the name doesn't exist.
521                * We may need to strupper() or strlower() it in case
522            * this conversion is being used for file creation 
523            * purposes. If the filename is of mixed case then 
524            * don't normalise it.
525            */
526
527           if (!case_preserve && (!strhasupper(start) || !strhaslower(start)))           
528             strnorm(start);
529
530           /*
531            * check on the mangled stack to see if we can recover the 
532            * base of the filename.
533            */
534
535           if (is_mangled(start)) {
536             check_mangled_cache( start );
537           }
538
539           DEBUG(5,("New file %s\n",start));
540           return(True); 
541         }
542
543       /* 
544        * Restore the rest of the string.
545        */
546       if (end) {
547         pstrcpy(start+strlen(start)+1,rest);
548         end = start + strlen(start);
549       }
550     } /* end else */
551
552     /* 
553      * Add to the dirpath that we have resolved so far.
554      */
555     if (*dirpath)
556       pstrcat(dirpath,"/");
557
558     pstrcat(dirpath,start);
559
560     /*
561      * Don't cache a name with mangled or wildcard components
562      * as this can change the size.
563      */
564
565     if(!component_was_mangled && !name_has_wildcard)
566       stat_cache_add(orig_path, dirpath);
567
568     /* 
569      * Restore the / that we wiped out earlier.
570      */
571     if (end)
572       *end = '/';
573   }
574   
575   /*
576    * Don't cache a name with mangled or wildcard components
577    * as this can change the size.
578    */
579
580   if(!component_was_mangled && !name_has_wildcard)
581     stat_cache_add(orig_path, name);
582
583   /* 
584    * The name has been resolved.
585    */
586
587   DEBUG(5,("conversion finished %s -> %s\n",orig_path, name));
588   return(True);
589 }
590
591
592 /****************************************************************************
593 check a filename - possibly caling reducename
594
595 This is called by every routine before it allows an operation on a filename.
596 It does any final confirmation necessary to ensure that the filename is
597 a valid one for the user to access.
598 ****************************************************************************/
599 BOOL check_name(char *name,connection_struct *conn)
600 {
601   BOOL ret;
602
603   errno = 0;
604
605   if (IS_VETO_PATH(conn, name))  {
606           DEBUG(5,("file path name %s vetoed\n",name));
607           return(0);
608   }
609
610   ret = reduce_name(name,conn->connectpath,lp_widelinks(SNUM(conn)));
611
612   /* Check if we are allowing users to follow symlinks */
613   /* Patch from David Clerc <David.Clerc@cui.unige.ch>
614      University of Geneva */
615
616 #ifdef S_ISLNK
617   if (!lp_symlinks(SNUM(conn)))
618     {
619       SMB_STRUCT_STAT statbuf;
620       if ( (dos_lstat(name,&statbuf) != -1) &&
621           (S_ISLNK(statbuf.st_mode)) )
622         {
623           DEBUG(3,("check_name: denied: file path name %s is a symlink\n",name));
624           ret=0; 
625         }
626     }
627 #endif
628
629   if (!ret)
630     DEBUG(5,("check_name on %s failed\n",name));
631
632   return(ret);
633 }
634
635
636 /****************************************************************************
637 scan a directory to find a filename, matching without case sensitivity
638
639 If the name looks like a mangled name then try via the mangling functions
640 ****************************************************************************/
641 static BOOL scan_directory(char *path, char *name,connection_struct *conn,BOOL docache)
642 {
643   void *cur_dir;
644   char *dname;
645   BOOL mangled;
646   pstring name2;
647
648   mangled = is_mangled(name);
649
650   /* handle null paths */
651   if (*path == 0)
652     path = ".";
653
654   if (docache && (dname = DirCacheCheck(path,name,SNUM(conn)))) {
655     pstrcpy(name, dname);       
656     return(True);
657   }      
658
659   /*
660    * The incoming name can be mangled, and if we de-mangle it
661    * here it will not compare correctly against the filename (name2)
662    * read from the directory and then mangled by the name_map_mangle()
663    * call. We need to mangle both names or neither.
664    * (JRA).
665    */
666   if (mangled)
667     mangled = !check_mangled_cache( name );
668
669   /* open the directory */
670   if (!(cur_dir = OpenDir(conn, path, True))) 
671     {
672       DEBUG(3,("scan dir didn't open dir [%s]\n",path));
673       return(False);
674     }
675
676   /* now scan for matching names */
677   while ((dname = ReadDirName(cur_dir))) 
678     {
679       if (*dname == '.' &&
680           (strequal(dname,".") || strequal(dname,"..")))
681         continue;
682
683       pstrcpy(name2,dname);
684       if (!name_map_mangle(name2,False,SNUM(conn))) continue;
685
686       if ((mangled && mangled_equal(name,name2))
687           || fname_equal(name, name2))
688         {
689           /* we've found the file, change it's name and return */
690           if (docache) DirCacheAdd(path,name,dname,SNUM(conn));
691           pstrcpy(name, dname);
692           CloseDir(cur_dir);
693           return(True);
694         }
695     }
696
697   CloseDir(cur_dir);
698   return(False);
699 }