2 Unix SMB/Netbios implementation.
4 Directory handling routines
5 Copyright (C) Andrew Tridgell 1992-1998
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.
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.
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.
25 This module implements directory related functions for Samba.
28 typedef struct _dptr_struct {
29 struct _dptr_struct *next, *prev;
32 connection_struct *conn;
35 char *wcard; /* Field only used for trans2_ searches */
36 uint16 attr; /* Field only used for trans2_ searches */
40 static struct bitmap *dptr_bmap;
41 static dptr_struct *dirptrs;
43 static int dptrs_open = 0;
45 #define INVALID_DPTR_KEY (-3)
47 /****************************************************************************
48 Initialise the dir bitmap.
49 ****************************************************************************/
53 static BOOL dptrs_init=False;
58 dptr_bmap = bitmap_allocate(MAX_DIRECTORY_HANDLES);
61 exit_server("out of memory in init_dptrs");
66 /****************************************************************************
67 Idle a dptr - the directory is closed but the control info is kept.
68 ****************************************************************************/
70 static void dptr_idle(dptr_struct *dptr)
73 DEBUG(4,("Idling dptr dnum %d\n",dptr->dnum));
80 /****************************************************************************
82 ****************************************************************************/
84 static void dptr_idleoldest(void)
89 * Go to the end of the list.
91 for(dptr = dirptrs; dptr && dptr->next; dptr = dptr->next)
95 DEBUG(0,("No dptrs available to idle ?\n"));
100 * Idle the oldest pointer.
103 for(; dptr; dptr = dptr->prev) {
111 /****************************************************************************
112 Get the dptr_struct for a dir index.
113 ****************************************************************************/
115 static dptr_struct *dptr_get(int key, BOOL forclose)
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)
124 DEBUG(4,("Reopening dptr key %d\n",key));
125 if ((dptr->ptr = OpenDir(dptr->conn, dptr->path, True)))
128 DLIST_PROMOTE(dirptrs,dptr);
135 /****************************************************************************
136 Get the dptr ptr for a dir index.
137 ****************************************************************************/
139 static void *dptr_ptr(int key)
141 dptr_struct *dptr = dptr_get(key, False);
148 /****************************************************************************
149 Get the dir path for a dir index.
150 ****************************************************************************/
152 char *dptr_path(int key)
154 dptr_struct *dptr = dptr_get(key, False);
161 /****************************************************************************
162 Get the dir wcard for a dir index (lanman2 specific).
163 ****************************************************************************/
165 char *dptr_wcard(int key)
167 dptr_struct *dptr = dptr_get(key, False);
174 /****************************************************************************
175 Set the dir wcard for a dir index (lanman2 specific).
176 Returns 0 on ok, 1 on fail.
177 ****************************************************************************/
179 BOOL dptr_set_wcard(int key, char *wcard)
181 dptr_struct *dptr = dptr_get(key, False);
190 /****************************************************************************
191 Set the dir attrib for a dir index (lanman2 specific).
192 Returns 0 on ok, 1 on fail.
193 ****************************************************************************/
195 BOOL dptr_set_attr(int key, uint16 attr)
197 dptr_struct *dptr = dptr_get(key, False);
206 /****************************************************************************
207 Get the dir attrib for a dir index (lanman2 specific)
208 ****************************************************************************/
210 uint16 dptr_attr(int key)
212 dptr_struct *dptr = dptr_get(key, False);
219 /****************************************************************************
220 Close a dptr (internal func).
221 ****************************************************************************/
223 static void dptr_close_internal(dptr_struct *dptr)
225 DEBUG(4,("closing dptr key %d\n",dptr->dnum));
227 DLIST_REMOVE(dirptrs, dptr);
230 * Free the dnum in the bitmap. Remember the dnum value is always
231 * biased by one with respect to the bitmap.
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",
239 bitmap_clear(dptr_bmap, dptr->dnum - 1);
246 /* Lanman 2 specific code */
247 SAFE_FREE(dptr->wcard);
248 string_set(&dptr->path,"");
252 /****************************************************************************
253 Close a dptr given a key.
254 ****************************************************************************/
256 void dptr_close(int *key)
260 if(*key == INVALID_DPTR_KEY)
263 /* OS/2 seems to use -1 to indicate "close all directories" */
266 for(dptr = dirptrs; dptr; dptr = next) {
268 dptr_close_internal(dptr);
270 *key = INVALID_DPTR_KEY;
274 dptr = dptr_get(*key, True);
277 DEBUG(0,("Invalid key %d given to dptr_close\n", *key));
281 dptr_close_internal(dptr);
283 *key = INVALID_DPTR_KEY;
286 /****************************************************************************
287 Close all dptrs for a cnum.
288 ****************************************************************************/
290 void dptr_closecnum(connection_struct *conn)
292 dptr_struct *dptr, *next;
293 for(dptr = dirptrs; dptr; dptr = next) {
295 if (dptr->conn == conn)
296 dptr_close_internal(dptr);
300 /****************************************************************************
301 Idle all dptrs for a cnum.
302 ****************************************************************************/
304 void dptr_idlecnum(connection_struct *conn)
307 for(dptr = dirptrs; dptr; dptr = dptr->next) {
308 if (dptr->conn == conn && dptr->ptr)
313 /****************************************************************************
314 Close a dptr that matches a given path, only if it matches the spid also.
315 ****************************************************************************/
317 void dptr_closepath(char *path,uint16 spid)
319 dptr_struct *dptr, *next;
320 for(dptr = dirptrs; dptr; dptr = next) {
322 if (spid == dptr->spid && strequal(dptr->path,path))
323 dptr_close_internal(dptr);
327 /****************************************************************************
328 Start a directory listing.
329 ****************************************************************************/
331 static BOOL start_dir(connection_struct *conn,char *directory)
333 DEBUG(5,("start_dir dir=%s\n",directory));
335 if (!check_name(directory,conn))
341 conn->dirptr = OpenDir(conn, directory, True);
344 string_set(&conn->dirpath,directory);
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 ****************************************************************************/
357 static void dptr_close_oldest(BOOL old)
362 * Go to the end of the list.
364 for(dptr = dirptrs; dptr && dptr->next; dptr = dptr->next)
368 DEBUG(0,("No old dptrs available to close oldest ?\n"));
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.
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);
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 ****************************************************************************/
396 int dptr_create(connection_struct *conn,char *path, BOOL old_handle, BOOL expect_close,uint16 spid)
400 if (!start_dir(conn,path))
401 return(-2); /* Code to say use a unix error return code. */
403 if (dptrs_open >= MAX_OPEN_DIRECTORIES)
406 dptr = (dptr_struct *)malloc(sizeof(dptr_struct));
408 DEBUG(0,("malloc fail in dptr_create.\n"));
417 * This is an old-style SMBsearch request. Ensure the
418 * value we return will fit in the range 1-255.
421 dptr->dnum = bitmap_find(dptr_bmap, 0);
423 if(dptr->dnum == -1 || dptr->dnum > 254) {
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.
431 dptr_close_oldest(True);
433 /* Now try again... */
434 dptr->dnum = bitmap_find(dptr_bmap, 0);
436 if(dptr->dnum == -1 || dptr->dnum > 254) {
437 DEBUG(0,("dptr_create: returned %d: Error - all old dirptrs in use ?\n", dptr->dnum));
445 * This is a new-style trans2 request. Allocate from
446 * a range that will return 256 - MAX_DIRECTORY_HANDLES.
449 dptr->dnum = bitmap_find(dptr_bmap, 255);
451 if(dptr->dnum == -1 || dptr->dnum < 255) {
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
460 dptr_close_oldest(False);
462 /* Now try again... */
463 dptr->dnum = bitmap_find(dptr_bmap, 255);
465 if(dptr->dnum == -1 || dptr->dnum < 255) {
466 DEBUG(0,("dptr_create: returned %d: Error - all new dirptrs in use ?\n", dptr->dnum));
473 bitmap_set(dptr_bmap, dptr->dnum);
475 dptr->dnum += 1; /* Always bias the dnum by one - no zero dnums allowed. */
477 dptr->ptr = conn->dirptr;
478 string_set(&dptr->path,path);
481 dptr->expect_close = expect_close;
482 dptr->wcard = NULL; /* Only used in lanman2 searches */
483 dptr->attr = 0; /* Only used in lanman2 searches */
485 DLIST_ADD(dirptrs, dptr);
487 DEBUG(3,("creating new dirptr %d for path %s, expect_close = %d\n",
488 dptr->dnum,path,expect_close));
493 /****************************************************************************
494 Fill the 5 byte server reserved dptr field.
495 ****************************************************************************/
497 BOOL dptr_fill(char *buf1,unsigned int key)
499 unsigned char *buf = (unsigned char *)buf1;
500 void *p = dptr_ptr(key);
503 DEBUG(1,("filling null dirptr %d\n",key));
507 DEBUG(6,("fill on key %u dirptr 0x%lx now at %d\n",key,
508 (long)p,(int)offset));
510 SIVAL(buf,1,offset | DPTR_MASK);
514 /****************************************************************************
515 Fetch the dir ptr and seek it given the 5 byte server field.
516 ****************************************************************************/
518 void *dptr_fetch(char *buf,int *num)
520 unsigned int key = *(unsigned char *)buf;
521 void *p = dptr_ptr(key);
524 DEBUG(3,("fetched null dirptr %d\n",key));
528 offset = IVAL(buf,1)&~DPTR_MASK;
530 DEBUG(3,("fetching dirptr %d for path %s at offset %d\n",
531 key,dptr_path(key),offset));
535 /****************************************************************************
537 ****************************************************************************/
539 void *dptr_fetch_lanman2(int dptr_num)
541 void *p = dptr_ptr(dptr_num);
544 DEBUG(3,("fetched null dirptr %d\n",dptr_num));
547 DEBUG(3,("fetching dirptr %d for path %s\n",dptr_num,dptr_path(dptr_num)));
551 /****************************************************************************
552 Check a filetype for being valid.
553 ****************************************************************************/
555 BOOL dir_check_ftype(connection_struct *conn,int mode,SMB_STRUCT_STAT *st,int dirtype)
557 if (((mode & ~dirtype) & (aHIDDEN | aSYSTEM | aDIR)) != 0)
562 /****************************************************************************
563 Get an 8.3 directory entry.
564 ****************************************************************************/
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)
571 SMB_STRUCT_STAT sbuf;
578 *path = *pathreal = *filename = 0;
580 isrootdir = (strequal(conn->dirpath,"./") ||
581 strequal(conn->dirpath,".") ||
582 strequal(conn->dirpath,"/"));
584 needslash = ( conn->dirpath[strlen(conn->dirpath) -1] != '/');
591 dname = ReadDirName(conn->dirptr);
593 DEBUG(6,("readdir on dirptr 0x%lx now at offset %d\n",
594 (long)conn->dirptr,TellDir(conn->dirptr)));
599 pstrcpy(filename,dname);
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
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)))
610 if (isrootdir && (strequal(filename,"..") || strequal(filename,".")))
613 if (!is_8_3(filename, False)) {
614 name_map_mangle(filename,True,False,SNUM(conn));
617 pstrcpy(fname,filename);
619 pstrcpy(path,conn->dirpath);
622 pstrcpy(pathreal,path);
624 pstrcat(pathreal,dname);
625 if (conn->vfs_ops.stat(conn, pathreal, &sbuf) != 0)
627 DEBUG(5,("Couldn't stat 1 [%s]. Error = %s\n",path, strerror(errno) ));
631 *mode = dos_mode(conn,pathreal,&sbuf);
633 if (!dir_check_ftype(conn,*mode,&sbuf,dirtype))
635 DEBUG(5,("[%s] attribs didn't match %x\n",filename,dirtype));
639 *size = sbuf.st_size;
640 *date = sbuf.st_mtime;
642 DEBUG(3,("get_dir_entry mask=[%s] found %s fname=%s\n",mask, pathreal,fname));
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 ********************************************************************/
670 static BOOL user_can_read_file(connection_struct *conn, char *name)
672 extern struct current_user current_user;
674 SEC_DESC *psd = NULL;
679 uint32 access_granted;
683 /* if we can't stat it does not show it */
684 if (vfs_stat(conn, name, &ste) != 0)
687 /* Pseudo-open the file (note - no fd's created). */
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);
693 fsp = open_file_stat(conn,name,&ste,DOS_OPEN_RDONLY,&smb_action);
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);
701 /* No access if SD get failed. */
705 return se_access_check(psd, current_user.nt_user_token, FILE_READ_DATA,
706 &access_granted, &status);
709 /* Old - crappy check :-). JRA */
711 if (ste.st_uid == conn->uid) {
712 return (ste.st_mode & S_IRUSR) == S_IRUSR;
715 if (ste.st_gid == conn->gid) {
716 return (ste.st_mode & S_IRGRP) == S_IRGRP;
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;
725 return (ste.st_mode & S_IROTH) == S_IROTH;
729 /*******************************************************************
731 ********************************************************************/
733 void *OpenDir(connection_struct *conn, char *name, BOOL use_veto)
737 DIR *p = conn->vfs_ops.opendir(conn,name);
740 if (!p) return(NULL);
741 dirp = (Dir *)malloc(sizeof(Dir));
743 DEBUG(0,("Out of memory in OpenDir\n"));
744 conn->vfs_ops.closedir(conn,p);
747 dirp->pos = dirp->numentries = dirp->mallocsize = 0;
748 dirp->data = dirp->current = NULL;
750 while ((n = vfs_readdirname(conn, p)))
756 /* If it's a vetoed file, pretend it doesn't even exist */
757 if (use_veto && conn && IS_VETO_PATH(conn, n)) continue;
759 /* Honour _hide unreadable_ option */
760 if (conn && lp_hideunreadable(SNUM(conn))) {
764 if (asprintf(&entry, "%s/%s/%s", conn->origpath, name, n) > 0) {
765 ret = user_can_read_file(conn, entry);
771 if (used + l > dirp->mallocsize) {
772 int s = MAX(used+l,used+2000);
774 r = (char *)Realloc(dirp->data,s);
776 DEBUG(0,("Out of memory in OpenDir\n"));
780 dirp->mallocsize = s;
781 dirp->current = dirp->data;
783 pstrcpy(dirp->data+used,n);
788 conn->vfs_ops.closedir(conn,p);
789 return((void *)dirp);
793 /*******************************************************************
795 ********************************************************************/
797 void CloseDir(void *p)
800 SAFE_FREE(((Dir *)p)->data);
804 /*******************************************************************
805 Read from a directory.
806 ********************************************************************/
808 char *ReadDirName(void *p)
811 Dir *dirp = (Dir *)p;
813 if (!dirp || !dirp->current || dirp->pos >= dirp->numentries) return(NULL);
816 dirp->current = skip_string(dirp->current,1);
823 /*******************************************************************
825 ********************************************************************/
827 BOOL SeekDir(void *p,int pos)
829 Dir *dirp = (Dir *)p;
831 if (!dirp) return(False);
833 if (pos < dirp->pos) {
834 dirp->current = dirp->data;
838 while (dirp->pos < pos && ReadDirName(p)) ;
840 return(dirp->pos == pos);
843 /*******************************************************************
845 ********************************************************************/
849 Dir *dirp = (Dir *)p;
851 if (!dirp) return(-1);
856 /*******************************************************************************
857 This section manages a global directory cache.
858 (It should probably be split into a separate module. crh)
859 ********************************************************************************/
869 static ubi_dlNewList( dir_cache );
871 /*****************************************************************************
872 Add an entry to the directory cache.
878 *****************************************************************************/
880 void DirCacheAdd( char *path, char *name, char *dname, int snum )
884 dir_cache_entry *entry;
886 /* Allocate the structure & string space in one go so that it can be freed
887 * in one call to free().
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 )
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. */
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);
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 ) );
908 /* Free excess cache entries. */
909 while( DIRCACHESIZE < dir_cache->count )
910 safe_free( ubi_dlRemTail( dir_cache ) );
914 /*****************************************************************************
915 Search for an entry to the directory cache.
919 Output: The dname string of the located entry, or NULL if the entry was
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
925 *****************************************************************************/
927 char *DirCacheCheck( char *path, char *name, int snum )
929 dir_cache_entry *entry;
931 for( entry = (dir_cache_entry *)ubi_dlFirst( dir_cache );
933 entry = (dir_cache_entry *)ubi_dlNext( entry ) )
935 if( entry->snum == snum
936 && 0 == strcmp( name, entry->name )
937 && 0 == strcmp( path, entry->path ) )
939 DEBUG(4, ("Got dir cache hit on %s %s -> %s\n",path,name,entry->dname));
940 return( entry->dname );
947 /*****************************************************************************
948 Remove all cache entries which have an snum that matches the input.
951 *****************************************************************************/
953 void DirCacheFlush(int snum)
955 dir_cache_entry *entry;
958 for(entry = (dir_cache_entry *)ubi_dlFirst( dir_cache );
960 next = ubi_dlNext( entry );
961 if( entry->snum == snum )
962 safe_free( ubi_dlRemThis( dir_cache, entry ) );
963 entry = (dir_cache_entry *)next;