faf5bca52d0c758606817dcae98784fbd9eb1ad4
[samba.git] / source3 / smbd / dir.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Directory 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 /*
25    This module implements directory related functions for Samba.
26 */
27
28 typedef struct _dptr_struct {
29         struct _dptr_struct *next, *prev;
30         int dnum;
31         uint16 spid;
32         connection_struct *conn;
33         void *ptr;
34         BOOL expect_close;
35         char *wcard; /* Field only used for trans2_ searches */
36         uint16 attr; /* Field only used for trans2_ searches */
37         char *path;
38 } dptr_struct;
39
40 static struct bitmap *dptr_bmap;
41 static dptr_struct *dirptrs;
42
43 static int dptrs_open = 0;
44
45 #define INVALID_DPTR_KEY (-3)
46
47 /****************************************************************************
48  Initialise the dir bitmap.
49 ****************************************************************************/
50
51 void init_dptrs(void)
52 {
53   static BOOL dptrs_init=False;
54
55   if (dptrs_init)
56     return;
57
58   dptr_bmap = bitmap_allocate(MAX_DIRECTORY_HANDLES);
59
60   if (!dptr_bmap)
61     exit_server("out of memory in init_dptrs");
62
63   dptrs_init = True;
64 }
65
66 /****************************************************************************
67  Idle a dptr - the directory is closed but the control info is kept.
68 ****************************************************************************/
69
70 static void dptr_idle(dptr_struct *dptr)
71 {
72   if (dptr->ptr) {
73     DEBUG(4,("Idling dptr dnum %d\n",dptr->dnum));
74     dptrs_open--;
75     CloseDir(dptr->ptr);
76     dptr->ptr = NULL;
77   }
78 }
79
80 /****************************************************************************
81  Idle the oldest dptr.
82 ****************************************************************************/
83
84 static void dptr_idleoldest(void)
85 {
86   dptr_struct *dptr;
87
88   /*
89    * Go to the end of the list.
90    */
91   for(dptr = dirptrs; dptr && dptr->next; dptr = dptr->next)
92     ;
93
94   if(!dptr) {
95     DEBUG(0,("No dptrs available to idle ?\n"));
96     return;
97   }
98
99   /*
100    * Idle the oldest pointer.
101    */
102
103   for(; dptr; dptr = dptr->prev) {
104     if (dptr->ptr) {
105       dptr_idle(dptr);
106       return;
107     }
108   }
109 }
110
111 /****************************************************************************
112  Get the dptr_struct for a dir index.
113 ****************************************************************************/
114
115 static dptr_struct *dptr_get(int key, BOOL forclose)
116 {
117   dptr_struct *dptr;
118
119   for(dptr = dirptrs; dptr; dptr = dptr->next) {
120     if(dptr->dnum == key) {
121       if (!forclose && !dptr->ptr) {
122         if (dptrs_open >= MAX_OPEN_DIRECTORIES)
123           dptr_idleoldest();
124         DEBUG(4,("Reopening dptr key %d\n",key));
125         if ((dptr->ptr = OpenDir(dptr->conn, dptr->path, True)))
126           dptrs_open++;
127       }
128       DLIST_PROMOTE(dirptrs,dptr);
129       return dptr;
130     }
131   }
132   return(NULL);
133 }
134
135 /****************************************************************************
136  Get the dptr ptr for a dir index.
137 ****************************************************************************/
138
139 static void *dptr_ptr(int key)
140 {
141   dptr_struct *dptr = dptr_get(key, False);
142
143   if (dptr)
144     return(dptr->ptr);
145   return(NULL);
146 }
147
148 /****************************************************************************
149  Get the dir path for a dir index.
150 ****************************************************************************/
151
152 char *dptr_path(int key)
153 {
154   dptr_struct *dptr = dptr_get(key, False);
155
156   if (dptr)
157     return(dptr->path);
158   return(NULL);
159 }
160
161 /****************************************************************************
162  Get the dir wcard for a dir index (lanman2 specific).
163 ****************************************************************************/
164
165 char *dptr_wcard(int key)
166 {
167   dptr_struct *dptr = dptr_get(key, False);
168
169   if (dptr)
170     return(dptr->wcard);
171   return(NULL);
172 }
173
174 /****************************************************************************
175  Set the dir wcard for a dir index (lanman2 specific).
176  Returns 0 on ok, 1 on fail.
177 ****************************************************************************/
178
179 BOOL dptr_set_wcard(int key, char *wcard)
180 {
181   dptr_struct *dptr = dptr_get(key, False);
182
183   if (dptr) {
184     dptr->wcard = wcard;
185     return True;
186   }
187   return False;
188 }
189
190 /****************************************************************************
191  Set the dir attrib for a dir index (lanman2 specific).
192  Returns 0 on ok, 1 on fail.
193 ****************************************************************************/
194
195 BOOL dptr_set_attr(int key, uint16 attr)
196 {
197   dptr_struct *dptr = dptr_get(key, False);
198
199   if (dptr) {
200     dptr->attr = attr;
201     return True;
202   }
203   return False;
204 }
205
206 /****************************************************************************
207  Get the dir attrib for a dir index (lanman2 specific)
208 ****************************************************************************/
209
210 uint16 dptr_attr(int key)
211 {
212   dptr_struct *dptr = dptr_get(key, False);
213
214   if (dptr)
215     return(dptr->attr);
216   return(0);
217 }
218
219 /****************************************************************************
220  Close a dptr (internal func).
221 ****************************************************************************/
222
223 static void dptr_close_internal(dptr_struct *dptr)
224 {
225   DEBUG(4,("closing dptr key %d\n",dptr->dnum));
226
227   DLIST_REMOVE(dirptrs, dptr);
228
229   /* 
230    * Free the dnum in the bitmap. Remember the dnum value is always 
231    * biased by one with respect to the bitmap.
232    */
233
234   if(bitmap_query( dptr_bmap, dptr->dnum - 1) != True) {
235     DEBUG(0,("dptr_close_internal : Error - closing dnum = %d and bitmap not set !\n",
236                         dptr->dnum ));
237   }
238
239   bitmap_clear(dptr_bmap, dptr->dnum - 1);
240
241   if (dptr->ptr) {
242     CloseDir(dptr->ptr);
243     dptrs_open--;
244   }
245
246   /* Lanman 2 specific code */
247   SAFE_FREE(dptr->wcard);
248   string_set(&dptr->path,"");
249   SAFE_FREE(dptr);
250 }
251
252 /****************************************************************************
253  Close a dptr given a key.
254 ****************************************************************************/
255
256 void dptr_close(int *key)
257 {
258   dptr_struct *dptr;
259
260   if(*key == INVALID_DPTR_KEY)
261     return;
262
263   /* OS/2 seems to use -1 to indicate "close all directories" */
264   if (*key == -1) {
265     dptr_struct *next;
266     for(dptr = dirptrs; dptr; dptr = next) {
267       next = dptr->next;
268       dptr_close_internal(dptr);
269     }
270     *key = INVALID_DPTR_KEY;
271     return;
272   }
273
274   dptr = dptr_get(*key, True);
275
276   if (!dptr) {
277     DEBUG(0,("Invalid key %d given to dptr_close\n", *key));
278     return;
279   }
280
281   dptr_close_internal(dptr);
282
283   *key = INVALID_DPTR_KEY;
284 }
285
286 /****************************************************************************
287  Close all dptrs for a cnum.
288 ****************************************************************************/
289
290 void dptr_closecnum(connection_struct *conn)
291 {
292   dptr_struct *dptr, *next;
293   for(dptr = dirptrs; dptr; dptr = next) {
294     next = dptr->next;
295     if (dptr->conn == conn)
296       dptr_close_internal(dptr);
297   }
298 }
299
300 /****************************************************************************
301  Idle all dptrs for a cnum.
302 ****************************************************************************/
303
304 void dptr_idlecnum(connection_struct *conn)
305 {
306   dptr_struct *dptr;
307   for(dptr = dirptrs; dptr; dptr = dptr->next) {
308     if (dptr->conn == conn && dptr->ptr)
309       dptr_idle(dptr);
310   }
311 }
312
313 /****************************************************************************
314  Close a dptr that matches a given path, only if it matches the spid also.
315 ****************************************************************************/
316
317 void dptr_closepath(char *path,uint16 spid)
318 {
319   dptr_struct *dptr, *next;
320   for(dptr = dirptrs; dptr; dptr = next) {
321     next = dptr->next;
322     if (spid == dptr->spid && strequal(dptr->path,path))
323       dptr_close_internal(dptr);
324   }
325 }
326
327 /****************************************************************************
328  Start a directory listing.
329 ****************************************************************************/
330
331 static BOOL start_dir(connection_struct *conn,char *directory)
332 {
333   DEBUG(5,("start_dir dir=%s\n",directory));
334
335   if (!check_name(directory,conn))
336     return(False);
337   
338   if (! *directory)
339     directory = ".";
340
341   conn->dirptr = OpenDir(conn, directory, True);
342   if (conn->dirptr) {    
343     dptrs_open++;
344     string_set(&conn->dirpath,directory);
345     return(True);
346   }
347   
348   return(False);
349 }
350
351 /****************************************************************************
352  Try and close the oldest handle not marked for
353  expect close in the hope that the client has
354  finished with that one.
355 ****************************************************************************/
356
357 static void dptr_close_oldest(BOOL old)
358 {
359   dptr_struct *dptr;
360
361   /*
362    * Go to the end of the list.
363    */
364   for(dptr = dirptrs; dptr && dptr->next; dptr = dptr->next)
365     ;
366
367   if(!dptr) {
368     DEBUG(0,("No old dptrs available to close oldest ?\n"));
369     return;
370   }
371
372   /*
373    * If 'old' is true, close the oldest oldhandle dnum (ie. 1 < dnum < 256) that
374    * does not have expect_close set. If 'old' is false, close
375    * one of the new dnum handles.
376    */
377
378   for(; dptr; dptr = dptr->prev) {
379     if ((old && (dptr->dnum < 256) && !dptr->expect_close) ||
380         (!old && (dptr->dnum > 255))) {
381       dptr_close_internal(dptr);
382       return;
383     }
384   }
385 }
386
387 /****************************************************************************
388  Create a new dir ptr. If the flag old_handle is true then we must allocate
389  from the bitmap range 0 - 255 as old SMBsearch directory handles are only
390  one byte long. If old_handle is false we allocate from the range
391  256 - MAX_DIRECTORY_HANDLES. We bias the number we return by 1 to ensure
392  a directory handle is never zero. All the above is folklore taught to
393  me at Andrew's knee.... :-) :-). JRA.
394 ****************************************************************************/
395
396 int dptr_create(connection_struct *conn,char *path, BOOL old_handle, BOOL expect_close,uint16 spid)
397 {
398   dptr_struct *dptr;
399
400   if (!start_dir(conn,path))
401     return(-2); /* Code to say use a unix error return code. */
402
403   if (dptrs_open >= MAX_OPEN_DIRECTORIES)
404     dptr_idleoldest();
405
406   dptr = (dptr_struct *)malloc(sizeof(dptr_struct));
407   if(!dptr) {
408     DEBUG(0,("malloc fail in dptr_create.\n"));
409     return -1;
410   }
411
412   ZERO_STRUCTP(dptr);
413
414   if(old_handle) {
415
416     /*
417      * This is an old-style SMBsearch request. Ensure the
418      * value we return will fit in the range 1-255.
419      */
420
421     dptr->dnum = bitmap_find(dptr_bmap, 0);
422
423     if(dptr->dnum == -1 || dptr->dnum > 254) {
424
425       /*
426        * Try and close the oldest handle not marked for
427        * expect close in the hope that the client has
428        * finished with that one.
429        */
430
431       dptr_close_oldest(True);
432
433       /* Now try again... */
434       dptr->dnum = bitmap_find(dptr_bmap, 0);
435
436       if(dptr->dnum == -1 || dptr->dnum > 254) {
437         DEBUG(0,("dptr_create: returned %d: Error - all old dirptrs in use ?\n", dptr->dnum));
438         SAFE_FREE(dptr);
439         return -1;
440       }
441     }
442   } else {
443
444     /*
445      * This is a new-style trans2 request. Allocate from
446      * a range that will return 256 - MAX_DIRECTORY_HANDLES.
447      */
448
449     dptr->dnum = bitmap_find(dptr_bmap, 255);
450
451     if(dptr->dnum == -1 || dptr->dnum < 255) {
452
453       /*
454        * Try and close the oldest handle close in the hope that
455        * the client has finished with that one. This will only
456        * happen in the case of the Win98 client bug where it leaks
457        * directory handles.
458        */
459
460       dptr_close_oldest(False);
461
462       /* Now try again... */
463       dptr->dnum = bitmap_find(dptr_bmap, 255);
464
465       if(dptr->dnum == -1 || dptr->dnum < 255) {
466         DEBUG(0,("dptr_create: returned %d: Error - all new dirptrs in use ?\n", dptr->dnum));
467         SAFE_FREE(dptr);
468         return -1;
469       }
470     }
471   }
472
473   bitmap_set(dptr_bmap, dptr->dnum);
474
475   dptr->dnum += 1; /* Always bias the dnum by one - no zero dnums allowed. */
476
477   dptr->ptr = conn->dirptr;
478   string_set(&dptr->path,path);
479   dptr->conn = conn;
480   dptr->spid = spid;
481   dptr->expect_close = expect_close;
482   dptr->wcard = NULL; /* Only used in lanman2 searches */
483   dptr->attr = 0; /* Only used in lanman2 searches */
484
485   DLIST_ADD(dirptrs, dptr);
486
487   DEBUG(3,("creating new dirptr %d for path %s, expect_close = %d\n",
488            dptr->dnum,path,expect_close));  
489
490   return(dptr->dnum);
491 }
492
493 /****************************************************************************
494  Fill the 5 byte server reserved dptr field.
495 ****************************************************************************/
496
497 BOOL dptr_fill(char *buf1,unsigned int key)
498 {
499   unsigned char *buf = (unsigned char *)buf1;
500   void *p = dptr_ptr(key);
501   uint32 offset;
502   if (!p) {
503     DEBUG(1,("filling null dirptr %d\n",key));
504     return(False);
505   }
506   offset = TellDir(p);
507   DEBUG(6,("fill on key %u dirptr 0x%lx now at %d\n",key,
508            (long)p,(int)offset));
509   buf[0] = key;
510   SIVAL(buf,1,offset | DPTR_MASK);
511   return(True);
512 }
513
514 /****************************************************************************
515  Fetch the dir ptr and seek it given the 5 byte server field.
516 ****************************************************************************/
517
518 void *dptr_fetch(char *buf,int *num)
519 {
520   unsigned int key = *(unsigned char *)buf;
521   void *p = dptr_ptr(key);
522   uint32 offset;
523   if (!p) {
524     DEBUG(3,("fetched null dirptr %d\n",key));
525     return(NULL);
526   }
527   *num = key;
528   offset = IVAL(buf,1)&~DPTR_MASK;
529   SeekDir(p,offset);
530   DEBUG(3,("fetching dirptr %d for path %s at offset %d\n",
531            key,dptr_path(key),offset));
532   return(p);
533 }
534
535 /****************************************************************************
536  Fetch the dir ptr.
537 ****************************************************************************/
538
539 void *dptr_fetch_lanman2(int dptr_num)
540 {
541   void *p = dptr_ptr(dptr_num);
542
543   if (!p) {
544     DEBUG(3,("fetched null dirptr %d\n",dptr_num));
545     return(NULL);
546   }
547   DEBUG(3,("fetching dirptr %d for path %s\n",dptr_num,dptr_path(dptr_num)));
548   return(p);
549 }
550
551 /****************************************************************************
552  Check a filetype for being valid.
553 ****************************************************************************/
554
555 BOOL dir_check_ftype(connection_struct *conn,int mode,SMB_STRUCT_STAT *st,int dirtype)
556 {
557   if (((mode & ~dirtype) & (aHIDDEN | aSYSTEM | aDIR)) != 0)
558     return False;
559   return True;
560 }
561
562 /****************************************************************************
563  Get an 8.3 directory entry.
564 ****************************************************************************/
565
566 BOOL get_dir_entry(connection_struct *conn,char *mask,int dirtype,char *fname,
567                    SMB_OFF_T *size,int *mode,time_t *date,BOOL check_descend)
568 {
569   char *dname;
570   BOOL found = False;
571   SMB_STRUCT_STAT sbuf;
572   pstring path;
573   pstring pathreal;
574   BOOL isrootdir;
575   pstring filename;
576   BOOL needslash;
577
578   *path = *pathreal = *filename = 0;
579
580   isrootdir = (strequal(conn->dirpath,"./") ||
581                strequal(conn->dirpath,".") ||
582                strequal(conn->dirpath,"/"));
583   
584   needslash = ( conn->dirpath[strlen(conn->dirpath) -1] != '/');
585
586   if (!conn->dirptr)
587     return(False);
588
589   while (!found)
590   {
591     dname = ReadDirName(conn->dirptr);
592
593     DEBUG(6,("readdir on dirptr 0x%lx now at offset %d\n",
594           (long)conn->dirptr,TellDir(conn->dirptr)));
595       
596     if (dname == NULL) 
597       return(False);
598       
599     pstrcpy(filename,dname);      
600
601     /* notice the special *.* handling. This appears to be the only difference
602        between the wildcard handling in this routine and in the trans2 routines.
603        see masktest for a demo
604     */
605     if ((strcmp(mask,"*.*") == 0) ||
606         mask_match(filename,mask,False) ||
607         (name_map_mangle(filename,True,False,SNUM(conn)) &&
608          mask_match(filename,mask,False)))
609     {
610       if (isrootdir && (strequal(filename,"..") || strequal(filename,".")))
611         continue;
612
613       if (!is_8_3(filename, False)) {
614               name_map_mangle(filename,True,False,SNUM(conn));
615       }
616
617       pstrcpy(fname,filename);
618       *path = 0;
619       pstrcpy(path,conn->dirpath);
620       if(needslash)
621         pstrcat(path,"/");
622       pstrcpy(pathreal,path);
623       pstrcat(path,fname);
624       pstrcat(pathreal,dname);
625       if (conn->vfs_ops.stat(conn, pathreal, &sbuf) != 0)
626       {
627         DEBUG(5,("Couldn't stat 1 [%s]. Error = %s\n",path, strerror(errno) ));
628         continue;
629       }
630           
631       *mode = dos_mode(conn,pathreal,&sbuf);
632
633       if (!dir_check_ftype(conn,*mode,&sbuf,dirtype)) 
634       {
635         DEBUG(5,("[%s] attribs didn't match %x\n",filename,dirtype));
636         continue;
637       }
638
639       *size = sbuf.st_size;
640       *date = sbuf.st_mtime;
641
642       DEBUG(3,("get_dir_entry mask=[%s] found %s fname=%s\n",mask, pathreal,fname));
643           
644       found = True;
645     }
646   }
647
648   return(found);
649 }
650
651
652
653 typedef struct
654 {
655   int pos;
656   int numentries;
657   int mallocsize;
658   char *data;
659   char *current;
660 } Dir;
661
662
663
664 /*******************************************************************
665 check to see if a user can read a file. This is only approximate,
666 it is used as part of the "hide unreadable" option. Don't
667 use it for anything security sensitive
668 ********************************************************************/
669
670 static BOOL user_can_read_file(connection_struct *conn, char *name)
671 {
672         extern struct current_user current_user;
673         SMB_STRUCT_STAT ste;
674         SEC_DESC *psd = NULL;
675         size_t sd_size;
676         files_struct *fsp;
677         int smb_action;
678         NTSTATUS status;
679         uint32 access_granted;
680
681         ZERO_STRUCT(ste);
682
683         /* if we can't stat it does not show it */
684         if (vfs_stat(conn, name, &ste) != 0)
685                 return False;
686
687         /* Pseudo-open the file (note - no fd's created). */
688
689         if(S_ISDIR(ste.st_mode))        
690                  fsp = open_directory(conn, name, &ste, SET_DENY_MODE(DENY_NONE), FILE_OPEN,
691                         unix_mode(conn,aRONLY|aDIR, name), &smb_action);
692         else
693                 fsp = open_file_stat(conn,name,&ste,DOS_OPEN_RDONLY,&smb_action);
694         if (!fsp)
695                 return False;
696
697         /* Get NT ACL -allocated in main loop talloc context. No free needed here. */
698         sd_size = conn->vfs_ops.fget_nt_acl(fsp, fsp->fd, &psd);
699         close_file(fsp, True);
700
701         /* No access if SD get failed. */
702         if (!sd_size)
703                 return False;
704
705         return se_access_check(psd, current_user.nt_user_token, FILE_READ_DATA,
706                                  &access_granted, &status);
707
708 #if 0
709         /* Old - crappy check :-). JRA */
710
711         if (ste.st_uid == conn->uid) {
712                 return (ste.st_mode & S_IRUSR) == S_IRUSR;
713         } else {
714                 int i;
715                 if (ste.st_gid == conn->gid) {
716                         return (ste.st_mode & S_IRGRP) == S_IRGRP;
717                 }
718                 for (i=0; i<conn->ngroups; i++) {
719                         if (conn->groups[i] == ste.st_gid) {
720                                 return (ste.st_mode & S_IRGRP) == S_IRGRP;
721                         }
722                 }
723         }
724
725         return (ste.st_mode & S_IROTH) == S_IROTH;
726 #endif
727 }
728
729 /*******************************************************************
730  Open a directory.
731 ********************************************************************/
732
733 void *OpenDir(connection_struct *conn, char *name, BOOL use_veto)
734 {
735   Dir *dirp;
736   char *n;
737   DIR *p = conn->vfs_ops.opendir(conn,name);
738   int used=0;
739
740   if (!p) return(NULL);
741   dirp = (Dir *)malloc(sizeof(Dir));
742   if (!dirp) {
743     DEBUG(0,("Out of memory in OpenDir\n"));
744     conn->vfs_ops.closedir(conn,p);
745     return(NULL);
746   }
747   dirp->pos = dirp->numentries = dirp->mallocsize = 0;
748   dirp->data = dirp->current = NULL;
749
750   while ((n = vfs_readdirname(conn, p)))
751   {
752     int l;
753
754     l = strlen(n)+1;
755
756     /* If it's a vetoed file, pretend it doesn't even exist */
757     if (use_veto && conn && IS_VETO_PATH(conn, n)) continue;
758
759     /* Honour _hide unreadable_ option */
760     if (conn && lp_hideunreadable(SNUM(conn))) {
761             char *entry;
762             int ret=0;
763       
764             if (asprintf(&entry, "%s/%s/%s", conn->origpath, name, n) > 0) {
765                     ret = user_can_read_file(conn, entry);
766                     SAFE_FREE(entry);
767             }
768             if (!ret) continue;
769     }
770
771     if (used + l > dirp->mallocsize) {
772       int s = MAX(used+l,used+2000);
773       char *r;
774       r = (char *)Realloc(dirp->data,s);
775       if (!r) {
776         DEBUG(0,("Out of memory in OpenDir\n"));
777         break;
778       }
779       dirp->data = r;
780       dirp->mallocsize = s;
781       dirp->current = dirp->data;
782     }
783     pstrcpy(dirp->data+used,n);
784     used += l;
785     dirp->numentries++;
786   }
787
788   conn->vfs_ops.closedir(conn,p);
789   return((void *)dirp);
790 }
791
792
793 /*******************************************************************
794  Close a directory.
795 ********************************************************************/
796
797 void CloseDir(void *p)
798 {
799   if (!p) return;    
800   SAFE_FREE(((Dir *)p)->data);
801   SAFE_FREE(p);
802 }
803
804 /*******************************************************************
805  Read from a directory.
806 ********************************************************************/
807
808 char *ReadDirName(void *p)
809 {
810   char *ret;
811   Dir *dirp = (Dir *)p;
812
813   if (!dirp || !dirp->current || dirp->pos >= dirp->numentries) return(NULL);
814
815   ret = dirp->current;
816   dirp->current = skip_string(dirp->current,1);
817   dirp->pos++;
818
819   return(ret);
820 }
821
822
823 /*******************************************************************
824  Seek a dir.
825 ********************************************************************/
826
827 BOOL SeekDir(void *p,int pos)
828 {
829   Dir *dirp = (Dir *)p;
830
831   if (!dirp) return(False);
832
833   if (pos < dirp->pos) {
834     dirp->current = dirp->data;
835     dirp->pos = 0;
836   }
837
838   while (dirp->pos < pos && ReadDirName(p)) ;
839
840   return(dirp->pos == pos);
841 }
842
843 /*******************************************************************
844  Tell a dir position.
845 ********************************************************************/
846
847 int TellDir(void *p)
848 {
849   Dir *dirp = (Dir *)p;
850
851   if (!dirp) return(-1);
852   
853   return(dirp->pos);
854 }
855
856 /*******************************************************************************
857  This section manages a global directory cache.
858  (It should probably be split into a separate module.  crh)
859 ********************************************************************************/
860
861 typedef struct {
862   ubi_dlNode  node;
863   char       *path;
864   char       *name;
865   char       *dname;
866   int         snum;
867 } dir_cache_entry;
868
869 static ubi_dlNewList( dir_cache );
870
871 /*****************************************************************************
872  Add an entry to the directory cache.
873  Input:  path  -
874          name  -
875          dname -
876          snum  -
877  Output: None.
878 *****************************************************************************/
879
880 void DirCacheAdd( char *path, char *name, char *dname, int snum )
881 {
882   int               pathlen;
883   int               namelen;
884   dir_cache_entry  *entry;
885
886   /* Allocate the structure & string space in one go so that it can be freed
887    * in one call to free().
888    */
889   pathlen = strlen( path ) +1;  /* Bytes required to store path (with nul). */
890   namelen = strlen( name ) +1;  /* Bytes required to store name (with nul). */
891   entry = (dir_cache_entry *)malloc( sizeof( dir_cache_entry )
892                                    + pathlen
893                                    + namelen
894                                    + strlen( dname ) +1 );
895   if( NULL == entry )   /* Not adding to the cache is not fatal,  */
896     return;             /* so just return as if nothing happened. */
897
898   /* Set pointers correctly and load values. */
899   entry->path  = pstrcpy( (char *)&entry[1],       path);
900   entry->name  = pstrcpy( &(entry->path[pathlen]), name);
901   entry->dname = pstrcpy( &(entry->name[namelen]), dname);
902   entry->snum  = snum;
903
904   /* Add the new entry to the linked list. */
905   (void)ubi_dlAddHead( dir_cache, entry );
906   DEBUG( 4, ("Added dir cache entry %s %s -> %s\n", path, name, dname ) );
907
908   /* Free excess cache entries. */
909   while( DIRCACHESIZE < dir_cache->count )
910     safe_free( ubi_dlRemTail( dir_cache ) );
911
912 }
913
914 /*****************************************************************************
915  Search for an entry to the directory cache.
916  Input:  path  -
917          name  -
918          snum  -
919  Output: The dname string of the located entry, or NULL if the entry was
920          not found.
921
922  Notes:  This uses a linear search, which is is okay because of
923          the small size of the cache.  Use a splay tree or hash
924          for large caches.
925 *****************************************************************************/
926
927 char *DirCacheCheck( char *path, char *name, int snum )
928 {
929   dir_cache_entry *entry;
930
931   for( entry = (dir_cache_entry *)ubi_dlFirst( dir_cache );
932        NULL != entry;
933        entry = (dir_cache_entry *)ubi_dlNext( entry ) )
934     {
935     if( entry->snum == snum
936         && 0 == strcmp( name, entry->name )
937         && 0 == strcmp( path, entry->path ) )
938       {
939       DEBUG(4, ("Got dir cache hit on %s %s -> %s\n",path,name,entry->dname));
940       return( entry->dname );
941       }
942     }
943
944   return(NULL);
945 }
946
947 /*****************************************************************************
948  Remove all cache entries which have an snum that matches the input.
949  Input:  snum  -
950  Output: None.
951 *****************************************************************************/
952
953 void DirCacheFlush(int snum)
954 {
955         dir_cache_entry *entry;
956         ubi_dlNodePtr    next;
957
958         for(entry = (dir_cache_entry *)ubi_dlFirst( dir_cache ); 
959             NULL != entry; )  {
960                 next = ubi_dlNext( entry );
961                 if( entry->snum == snum )
962                         safe_free( ubi_dlRemThis( dir_cache, entry ) );
963                 entry = (dir_cache_entry *)next;
964         }
965 }