s3: smbd: Reformat users of user_can_read_file().
[amitay/samba.git] / source3 / smbd / dir.c
1 /*
2    Unix SMB/CIFS implementation.
3    Directory handling routines
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2007
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 3 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, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/filesys.h"
23 #include "smbd/smbd.h"
24 #include "smbd/globals.h"
25 #include "libcli/security/security.h"
26 #include "lib/util/bitmap.h"
27 #include "../lib/util/memcache.h"
28 #include "../librpc/gen_ndr/open_files.h"
29
30 /*
31    This module implements directory related functions for Samba.
32 */
33
34 /* "Special" directory offsets. */
35 #define END_OF_DIRECTORY_OFFSET ((long)-1)
36 #define START_OF_DIRECTORY_OFFSET ((long)0)
37 #define DOT_DOT_DIRECTORY_OFFSET ((long)0x80000000)
38
39 /* "Special" directory offsets in 32-bit wire format. */
40 #define WIRE_END_OF_DIRECTORY_OFFSET ((uint32_t)0xFFFFFFFF)
41 #define WIRE_START_OF_DIRECTORY_OFFSET ((uint32_t)0)
42 #define WIRE_DOT_DOT_DIRECTORY_OFFSET ((uint32_t)0x80000000)
43
44 /* Make directory handle internals available. */
45
46 struct name_cache_entry {
47         char *name;
48         long offset;
49 };
50
51 struct smb_Dir {
52         connection_struct *conn;
53         DIR *dir;
54         long offset;
55         struct smb_filename *dir_smb_fname;
56         size_t name_cache_size;
57         struct name_cache_entry *name_cache;
58         unsigned int name_cache_index;
59         unsigned int file_number;
60         files_struct *fsp; /* Back pointer to containing fsp, only
61                               set from OpenDir_fsp(). */
62 };
63
64 struct dptr_struct {
65         struct dptr_struct *next, *prev;
66         int dnum;
67         uint16_t spid;
68         struct connection_struct *conn;
69         struct smb_Dir *dir_hnd;
70         bool expect_close;
71         char *wcard;
72         uint32_t attr;
73         struct smb_filename *smb_dname;
74         bool has_wild; /* Set to true if the wcard entry has MS wildcard characters in it. */
75         bool did_stat; /* Optimisation for non-wcard searches. */
76         bool priv;     /* Directory handle opened with privilege. */
77         uint32_t counter;
78         struct memcache *dptr_cache;
79 };
80
81 static struct smb_Dir *OpenDir_fsp(TALLOC_CTX *mem_ctx, connection_struct *conn,
82                         files_struct *fsp,
83                         const char *mask,
84                         uint32_t attr);
85
86 static void DirCacheAdd(struct smb_Dir *dir_hnd, const char *name, long offset);
87
88 static int smb_Dir_destructor(struct smb_Dir *dir_hnd);
89
90 #define INVALID_DPTR_KEY (-3)
91
92 /****************************************************************************
93  Initialise the dir bitmap.
94 ****************************************************************************/
95
96 bool init_dptrs(struct smbd_server_connection *sconn)
97 {
98         if (sconn->searches.dptr_bmap) {
99                 return true;
100         }
101
102         sconn->searches.dptr_bmap = bitmap_talloc(
103                 sconn, MAX_DIRECTORY_HANDLES);
104
105         if (sconn->searches.dptr_bmap == NULL) {
106                 return false;
107         }
108
109         return true;
110 }
111
112 /****************************************************************************
113  Get the struct dptr_struct for a dir index.
114 ****************************************************************************/
115
116 static struct dptr_struct *dptr_get(struct smbd_server_connection *sconn,
117                                     int key)
118 {
119         struct dptr_struct *dptr;
120
121         for (dptr = sconn->searches.dirptrs; dptr != NULL; dptr = dptr->next) {
122                 if(dptr->dnum != key) {
123                         continue;
124                 }
125                 DLIST_PROMOTE(sconn->searches.dirptrs, dptr);
126                 return dptr;
127         }
128         return(NULL);
129 }
130
131 /****************************************************************************
132  Get the dir path for a dir index.
133 ****************************************************************************/
134
135 const char *dptr_path(struct smbd_server_connection *sconn, int key)
136 {
137         struct dptr_struct *dptr = dptr_get(sconn, key);
138         if (dptr)
139                 return(dptr->smb_dname->base_name);
140         return(NULL);
141 }
142
143 /****************************************************************************
144  Get the dir wcard for a dir index.
145 ****************************************************************************/
146
147 const char *dptr_wcard(struct smbd_server_connection *sconn, int key)
148 {
149         struct dptr_struct *dptr = dptr_get(sconn, key);
150         if (dptr)
151                 return(dptr->wcard);
152         return(NULL);
153 }
154
155 /****************************************************************************
156  Get the dir attrib for a dir index.
157 ****************************************************************************/
158
159 uint16_t dptr_attr(struct smbd_server_connection *sconn, int key)
160 {
161         struct dptr_struct *dptr = dptr_get(sconn, key);
162         if (dptr)
163                 return(dptr->attr);
164         return(0);
165 }
166
167 /****************************************************************************
168  Close all dptrs for a cnum.
169 ****************************************************************************/
170
171 void dptr_closecnum(connection_struct *conn)
172 {
173         struct dptr_struct *dptr, *next;
174         struct smbd_server_connection *sconn = conn->sconn;
175
176         if (sconn == NULL) {
177                 return;
178         }
179
180         for(dptr = sconn->searches.dirptrs; dptr; dptr = next) {
181                 next = dptr->next;
182                 if (dptr->conn == conn) {
183                         files_struct *fsp = dptr->dir_hnd->fsp;
184                         close_file(NULL, fsp, NORMAL_CLOSE);
185                         fsp = NULL;
186                 }
187         }
188 }
189
190 /****************************************************************************
191  Create a new dir ptr. If the flag old_handle is true then we must allocate
192  from the bitmap range 0 - 255 as old SMBsearch directory handles are only
193  one byte long. If old_handle is false we allocate from the range
194  256 - MAX_DIRECTORY_HANDLES. We bias the number we return by 1 to ensure
195  a directory handle is never zero.
196  wcard must not be zero.
197 ****************************************************************************/
198
199 NTSTATUS dptr_create(connection_struct *conn,
200                 struct smb_request *req,
201                 files_struct *fsp,
202                 bool old_handle,
203                 bool expect_close,
204                 uint16_t spid,
205                 const char *wcard,
206                 bool wcard_has_wild,
207                 uint32_t attr,
208                 struct dptr_struct **dptr_ret)
209 {
210         struct smbd_server_connection *sconn = conn->sconn;
211         struct dptr_struct *dptr = NULL;
212         struct smb_Dir *dir_hnd;
213
214         DBG_INFO("dir=%s\n", fsp_str_dbg(fsp));
215
216         if (sconn == NULL) {
217                 DEBUG(0,("dptr_create: called with fake connection_struct\n"));
218                 return NT_STATUS_INTERNAL_ERROR;
219         }
220
221         if (!wcard) {
222                 return NT_STATUS_INVALID_PARAMETER;
223         }
224
225         if (!(fsp->access_mask & SEC_DIR_LIST)) {
226                 DBG_INFO("dptr_create: directory %s "
227                         "not open for LIST access\n",
228                         fsp_str_dbg(fsp));
229                 return NT_STATUS_ACCESS_DENIED;
230         }
231         dir_hnd = OpenDir_fsp(NULL, conn, fsp, wcard, attr);
232         if (!dir_hnd) {
233                 return map_nt_error_from_unix(errno);
234         }
235
236         dptr = talloc_zero(NULL, struct dptr_struct);
237         if(!dptr) {
238                 DEBUG(0,("talloc fail in dptr_create.\n"));
239                 TALLOC_FREE(dir_hnd);
240                 return NT_STATUS_NO_MEMORY;
241         }
242
243         dptr->smb_dname = cp_smb_filename(dptr, fsp->fsp_name);
244         if (dptr->smb_dname == NULL) {
245                 TALLOC_FREE(dptr);
246                 TALLOC_FREE(dir_hnd);
247                 return NT_STATUS_NO_MEMORY;
248         }
249         dptr->conn = conn;
250         dptr->dir_hnd = dir_hnd;
251         dptr->spid = spid;
252         dptr->expect_close = expect_close;
253         dptr->wcard = talloc_strdup(dptr, wcard);
254         if (!dptr->wcard) {
255                 TALLOC_FREE(dptr);
256                 TALLOC_FREE(dir_hnd);
257                 return NT_STATUS_NO_MEMORY;
258         }
259         if ((req != NULL && req->posix_pathnames) ||
260                         (wcard[0] == '.' && wcard[1] == 0)) {
261                 dptr->has_wild = True;
262         } else {
263                 dptr->has_wild = wcard_has_wild;
264         }
265
266         dptr->attr = attr;
267
268         if (sconn->using_smb2) {
269                 goto done;
270         }
271
272         if(old_handle) {
273
274                 /*
275                  * This is an old-style SMBsearch request. Ensure the
276                  * value we return will fit in the range 1-255.
277                  */
278
279                 dptr->dnum = bitmap_find(sconn->searches.dptr_bmap, 0);
280
281                 if(dptr->dnum == -1 || dptr->dnum > 254) {
282                         DBG_ERR("returned %d: Error - all old "
283                                 "dirptrs in use ?\n",
284                                 dptr->dnum);
285                         TALLOC_FREE(dptr);
286                         TALLOC_FREE(dir_hnd);
287                         return NT_STATUS_TOO_MANY_OPENED_FILES;
288                 }
289         } else {
290
291                 /*
292                  * This is a new-style trans2 request. Allocate from
293                  * a range that will return 256 - MAX_DIRECTORY_HANDLES.
294                  */
295
296                 dptr->dnum = bitmap_find(sconn->searches.dptr_bmap, 255);
297
298                 if(dptr->dnum == -1 || dptr->dnum < 255) {
299                         DBG_ERR("returned %d: Error - all new "
300                                 "dirptrs in use ?\n",
301                                 dptr->dnum);
302                         TALLOC_FREE(dptr);
303                         TALLOC_FREE(dir_hnd);
304                         return NT_STATUS_TOO_MANY_OPENED_FILES;
305                 }
306         }
307
308         bitmap_set(sconn->searches.dptr_bmap, dptr->dnum);
309
310         dptr->dnum += 1; /* Always bias the dnum by one - no zero dnums allowed. */
311
312         DLIST_ADD(sconn->searches.dirptrs, dptr);
313
314 done:
315         DBG_INFO("creating new dirptr [%d] for path [%s], expect_close = %d\n",
316                  dptr->dnum, fsp_str_dbg(fsp), expect_close);
317
318         *dptr_ret = dptr;
319
320         return NT_STATUS_OK;
321 }
322
323
324 /****************************************************************************
325  Wrapper functions to access the lower level directory handles.
326 ****************************************************************************/
327
328 void dptr_CloseDir(files_struct *fsp)
329 {
330         struct smbd_server_connection *sconn = NULL;
331
332         if (fsp->dptr == NULL) {
333                 return;
334         }
335         sconn = fsp->dptr->conn->sconn;
336
337         /*
338          * The destructor for the struct smb_Dir (fsp->dptr->dir_hnd)
339          * now handles all resource deallocation.
340          */
341
342         DBG_INFO("closing dptr key %d\n", fsp->dptr->dnum);
343
344         if (sconn != NULL && !sconn->using_smb2) {
345                 DLIST_REMOVE(sconn->searches.dirptrs, fsp->dptr);
346
347                 /*
348                  * Free the dnum in the bitmap. Remember the dnum value is
349                  * always biased by one with respect to the bitmap.
350                  */
351
352                 if (!bitmap_query(sconn->searches.dptr_bmap,
353                                   fsp->dptr->dnum - 1))
354                 {
355                         DBG_ERR("closing dnum = %d and bitmap not set !\n",
356                                 fsp->dptr->dnum);
357                 }
358
359                 bitmap_clear(sconn->searches.dptr_bmap, fsp->dptr->dnum - 1);
360         }
361
362         TALLOC_FREE(fsp->dptr->dir_hnd);
363         TALLOC_FREE(fsp->dptr);
364 }
365
366 void dptr_SeekDir(struct dptr_struct *dptr, long offset)
367 {
368         SeekDir(dptr->dir_hnd, offset);
369 }
370
371 long dptr_TellDir(struct dptr_struct *dptr)
372 {
373         return TellDir(dptr->dir_hnd);
374 }
375
376 bool dptr_has_wild(struct dptr_struct *dptr)
377 {
378         return dptr->has_wild;
379 }
380
381 int dptr_dnum(struct dptr_struct *dptr)
382 {
383         return dptr->dnum;
384 }
385
386 bool dptr_get_priv(struct dptr_struct *dptr)
387 {
388         return dptr->priv;
389 }
390
391 void dptr_set_priv(struct dptr_struct *dptr)
392 {
393         dptr->priv = true;
394 }
395
396 /****************************************************************************
397  Return the next visible file name, skipping veto'd and invisible files.
398 ****************************************************************************/
399
400 static const char *dptr_normal_ReadDirName(struct dptr_struct *dptr,
401                                            long *poffset, SMB_STRUCT_STAT *pst,
402                                            char **ptalloced)
403 {
404         /* Normal search for the next file. */
405         const char *name;
406         char *talloced = NULL;
407
408         while ((name = ReadDirName(dptr->dir_hnd, poffset, pst, &talloced))
409                != NULL) {
410                 if (is_visible_file(dptr->conn,
411                                 dptr->dir_hnd,
412                                 name,
413                                 pst,
414                                 true)) {
415                         *ptalloced = talloced;
416                         return name;
417                 }
418                 TALLOC_FREE(talloced);
419         }
420         return NULL;
421 }
422
423 /****************************************************************************
424  Return the next visible file name, skipping veto'd and invisible files.
425 ****************************************************************************/
426
427 static char *dptr_ReadDirName(TALLOC_CTX *ctx,
428                               struct dptr_struct *dptr,
429                               long *poffset,
430                               SMB_STRUCT_STAT *pst)
431 {
432         struct smb_filename smb_fname_base;
433         char *name = NULL;
434         const char *name_temp = NULL;
435         char *talloced = NULL;
436         char *pathreal = NULL;
437         char *found_name = NULL;
438         int ret;
439
440         SET_STAT_INVALID(*pst);
441
442         if (dptr->has_wild || dptr->did_stat) {
443                 name_temp = dptr_normal_ReadDirName(dptr, poffset, pst,
444                                                     &talloced);
445                 if (name_temp == NULL) {
446                         return NULL;
447                 }
448                 if (talloced != NULL) {
449                         return talloc_move(ctx, &talloced);
450                 }
451                 return talloc_strdup(ctx, name_temp);
452         }
453
454         /* If poffset is -1 then we know we returned this name before and we
455          * have no wildcards. We're at the end of the directory. */
456         if (*poffset == END_OF_DIRECTORY_OFFSET) {
457                 return NULL;
458         }
459
460         /* We know the stored wcard contains no wildcard characters.
461          * See if we can match with a stat call. If we can't, then set
462          * did_stat to true to ensure we only do this once and keep
463          * searching. */
464
465         dptr->did_stat = true;
466
467         /* First check if it should be visible. */
468         if (!is_visible_file(dptr->conn,
469                         dptr->dir_hnd,
470                         dptr->wcard,
471                         pst,
472                         true)) {
473                 /* This only returns false if the file was found, but
474                    is explicitly not visible. Set us to end of
475                    directory, but return NULL as we know we can't ever
476                    find it. */
477                 goto ret;
478         }
479
480         if (VALID_STAT(*pst)) {
481                 name = talloc_strdup(ctx, dptr->wcard);
482                 goto ret;
483         }
484
485         pathreal = talloc_asprintf(ctx,
486                                 "%s/%s",
487                                 dptr->smb_dname->base_name,
488                                 dptr->wcard);
489         if (!pathreal)
490                 return NULL;
491
492         /* Create an smb_filename with stream_name == NULL. */
493         smb_fname_base = (struct smb_filename) { .base_name = pathreal };
494
495         if (SMB_VFS_STAT(dptr->conn, &smb_fname_base) == 0) {
496                 *pst = smb_fname_base.st;
497                 name = talloc_strdup(ctx, dptr->wcard);
498                 goto clean;
499         } else {
500                 /* If we get any other error than ENOENT or ENOTDIR
501                    then the file exists we just can't stat it. */
502                 if (errno != ENOENT && errno != ENOTDIR) {
503                         name = talloc_strdup(ctx, dptr->wcard);
504                         goto clean;
505                 }
506         }
507
508         /* Stat failed. We know this is authoratiative if we are
509          * providing case sensitive semantics or the underlying
510          * filesystem is case sensitive.
511          */
512         if (dptr->conn->case_sensitive ||
513             !(dptr->conn->fs_capabilities & FILE_CASE_SENSITIVE_SEARCH))
514         {
515                 goto clean;
516         }
517
518         /*
519          * Try case-insensitive stat if the fs has the ability. This avoids
520          * scanning the whole directory.
521          */
522         ret = SMB_VFS_GET_REAL_FILENAME(dptr->conn,
523                                         dptr->smb_dname->base_name,
524                                         dptr->wcard,
525                                         ctx,
526                                         &found_name);
527         if (ret == 0) {
528                 name = found_name;
529                 goto clean;
530         } else if (errno == ENOENT) {
531                 /* The case-insensitive lookup was authoritative. */
532                 goto clean;
533         }
534
535         TALLOC_FREE(pathreal);
536
537         name_temp = dptr_normal_ReadDirName(dptr, poffset, pst, &talloced);
538         if (name_temp == NULL) {
539                 return NULL;
540         }
541         if (talloced != NULL) {
542                 return talloc_move(ctx, &talloced);
543         }
544         return talloc_strdup(ctx, name_temp);
545
546 clean:
547         TALLOC_FREE(pathreal);
548 ret:
549         /* We need to set the underlying dir_hnd offset to -1
550          * also as this function is usually called with the
551          * output from TellDir. */
552         dptr->dir_hnd->offset = *poffset = END_OF_DIRECTORY_OFFSET;
553         return name;
554 }
555
556 /****************************************************************************
557  Search for a file by name, skipping veto'ed and not visible files.
558 ****************************************************************************/
559
560 bool dptr_SearchDir(struct dptr_struct *dptr, const char *name, long *poffset, SMB_STRUCT_STAT *pst)
561 {
562         SET_STAT_INVALID(*pst);
563
564         if (!dptr->has_wild && (dptr->dir_hnd->offset == END_OF_DIRECTORY_OFFSET)) {
565                 /* This is a singleton directory and we're already at the end. */
566                 *poffset = END_OF_DIRECTORY_OFFSET;
567                 return False;
568         }
569
570         return SearchDir(dptr->dir_hnd, name, poffset);
571 }
572
573 /****************************************************************************
574  Map a native directory offset to a 32-bit cookie.
575 ****************************************************************************/
576
577 static uint32_t map_dir_offset_to_wire(struct dptr_struct *dptr, long offset)
578 {
579         DATA_BLOB key;
580         DATA_BLOB val;
581
582         if (offset == END_OF_DIRECTORY_OFFSET) {
583                 return WIRE_END_OF_DIRECTORY_OFFSET;
584         } else if(offset == START_OF_DIRECTORY_OFFSET) {
585                 return WIRE_START_OF_DIRECTORY_OFFSET;
586         } else if (offset == DOT_DOT_DIRECTORY_OFFSET) {
587                 return WIRE_DOT_DOT_DIRECTORY_OFFSET;
588         }
589         if (sizeof(long) == 4) {
590                 /* 32-bit machine. We can cheat... */
591                 return (uint32_t)offset;
592         }
593         if (dptr->dptr_cache == NULL) {
594                 /* Lazy initialize cache. */
595                 dptr->dptr_cache = memcache_init(dptr, 0);
596                 if (dptr->dptr_cache == NULL) {
597                         return WIRE_END_OF_DIRECTORY_OFFSET;
598                 }
599         } else {
600                 /* Have we seen this offset before ? */
601                 key.data = (void *)&offset;
602                 key.length = sizeof(offset);
603                 if (memcache_lookup(dptr->dptr_cache,
604                                         SMB1_SEARCH_OFFSET_MAP,
605                                         key,
606                                         &val)) {
607                         uint32_t wire_offset;
608                         SMB_ASSERT(val.length == sizeof(wire_offset));
609                         memcpy(&wire_offset, val.data, sizeof(wire_offset));
610                         DEBUG(10,("found wire %u <-> offset %ld\n",
611                                 (unsigned int)wire_offset,
612                                 (long)offset));
613                         return wire_offset;
614                 }
615         }
616         /* Allocate a new wire cookie. */
617         do {
618                 dptr->counter++;
619         } while (dptr->counter == WIRE_START_OF_DIRECTORY_OFFSET ||
620                  dptr->counter == WIRE_END_OF_DIRECTORY_OFFSET ||
621                  dptr->counter == WIRE_DOT_DOT_DIRECTORY_OFFSET);
622         /* Store it in the cache. */
623         key.data = (void *)&offset;
624         key.length = sizeof(offset);
625         val.data = (void *)&dptr->counter;
626         val.length = sizeof(dptr->counter); /* MUST BE uint32_t ! */
627         memcache_add(dptr->dptr_cache,
628                         SMB1_SEARCH_OFFSET_MAP,
629                         key,
630                         val);
631         /* And the reverse mapping for lookup from
632            map_wire_to_dir_offset(). */
633         memcache_add(dptr->dptr_cache,
634                         SMB1_SEARCH_OFFSET_MAP,
635                         val,
636                         key);
637         DEBUG(10,("stored wire %u <-> offset %ld\n",
638                 (unsigned int)dptr->counter,
639                 (long)offset));
640         return dptr->counter;
641 }
642
643 /****************************************************************************
644  Fill the 5 byte server reserved dptr field.
645 ****************************************************************************/
646
647 bool dptr_fill(struct smbd_server_connection *sconn,
648                char *buf1,unsigned int key)
649 {
650         unsigned char *buf = (unsigned char *)buf1;
651         struct dptr_struct *dptr = dptr_get(sconn, key);
652         uint32_t wire_offset;
653         if (!dptr) {
654                 DEBUG(1,("filling null dirptr %d\n",key));
655                 return(False);
656         }
657         wire_offset = map_dir_offset_to_wire(dptr,TellDir(dptr->dir_hnd));
658         DEBUG(6,("fill on key %u dirptr 0x%lx now at %d\n",key,
659                 (long)dptr->dir_hnd,(int)wire_offset));
660         buf[0] = key;
661         SIVAL(buf,1,wire_offset);
662         return(True);
663 }
664
665 /****************************************************************************
666  Map a 32-bit wire cookie to a native directory offset.
667 ****************************************************************************/
668
669 static long map_wire_to_dir_offset(struct dptr_struct *dptr, uint32_t wire_offset)
670 {
671         DATA_BLOB key;
672         DATA_BLOB val;
673
674         if (wire_offset == WIRE_END_OF_DIRECTORY_OFFSET) {
675                 return END_OF_DIRECTORY_OFFSET;
676         } else if(wire_offset == WIRE_START_OF_DIRECTORY_OFFSET) {
677                 return START_OF_DIRECTORY_OFFSET;
678         } else if (wire_offset == WIRE_DOT_DOT_DIRECTORY_OFFSET) {
679                 return DOT_DOT_DIRECTORY_OFFSET;
680         }
681         if (sizeof(long) == 4) {
682                 /* 32-bit machine. We can cheat... */
683                 return (long)wire_offset;
684         }
685         if (dptr->dptr_cache == NULL) {
686                 /* Logic error, cache should be initialized. */
687                 return END_OF_DIRECTORY_OFFSET;
688         }
689         key.data = (void *)&wire_offset;
690         key.length = sizeof(wire_offset);
691         if (memcache_lookup(dptr->dptr_cache,
692                                 SMB1_SEARCH_OFFSET_MAP,
693                                 key,
694                                 &val)) {
695                 /* Found mapping. */
696                 long offset;
697                 SMB_ASSERT(val.length == sizeof(offset));
698                 memcpy(&offset, val.data, sizeof(offset));
699                 DEBUG(10,("lookup wire %u <-> offset %ld\n",
700                         (unsigned int)wire_offset,
701                         (long)offset));
702                 return offset;
703         }
704         return END_OF_DIRECTORY_OFFSET;
705 }
706
707 /****************************************************************************
708  Return the associated fsp and seek the dir_hnd on it it given the 5 byte
709  server field.
710 ****************************************************************************/
711
712 files_struct *dptr_fetch_fsp(struct smbd_server_connection *sconn,
713                                char *buf, int *num)
714 {
715         unsigned int key = *(unsigned char *)buf;
716         struct dptr_struct *dptr = dptr_get(sconn, key);
717         uint32_t wire_offset;
718         long seekoff;
719
720         if (dptr == NULL) {
721                 DEBUG(3,("fetched null dirptr %d\n",key));
722                 return(NULL);
723         }
724         *num = key;
725         wire_offset = IVAL(buf,1);
726         seekoff = map_wire_to_dir_offset(dptr, wire_offset);
727         SeekDir(dptr->dir_hnd,seekoff);
728         DEBUG(3,("fetching dirptr %d for path %s at offset %d\n",
729                 key, dptr->smb_dname->base_name, (int)seekoff));
730         return dptr->dir_hnd->fsp;
731 }
732
733 /****************************************************************************
734  Fetch the fsp associated with the dptr_num.
735 ****************************************************************************/
736
737 files_struct *dptr_fetch_lanman2_fsp(struct smbd_server_connection *sconn,
738                                        int dptr_num)
739 {
740         struct dptr_struct *dptr  = dptr_get(sconn, dptr_num);
741         if (dptr == NULL) {
742                 return NULL;
743         }
744         DBG_NOTICE("fetching dirptr %d for path %s\n",
745                 dptr_num,
746                 dptr->smb_dname->base_name);
747         return dptr->dir_hnd->fsp;
748 }
749
750 static bool mangle_mask_match(connection_struct *conn,
751                 const char *filename,
752                 const char *mask)
753 {
754         char mname[13];
755
756         if (!name_to_8_3(filename,mname,False,conn->params)) {
757                 return False;
758         }
759         return mask_match_search(mname,mask,False);
760 }
761
762 bool smbd_dirptr_get_entry(TALLOC_CTX *ctx,
763                            struct dptr_struct *dirptr,
764                            const char *mask,
765                            uint32_t dirtype,
766                            bool dont_descend,
767                            bool ask_sharemode,
768                            bool get_dosmode,
769                            bool (*match_fn)(TALLOC_CTX *ctx,
770                                             void *private_data,
771                                             const char *dname,
772                                             const char *mask,
773                                             char **_fname),
774                            bool (*mode_fn)(TALLOC_CTX *ctx,
775                                            void *private_data,
776                                            struct smb_filename *smb_fname,
777                                            bool get_dosmode,
778                                            uint32_t *_mode),
779                            void *private_data,
780                            char **_fname,
781                            struct smb_filename **_smb_fname,
782                            uint32_t *_mode,
783                            long *_prev_offset)
784 {
785         connection_struct *conn = dirptr->conn;
786         size_t slashlen;
787         size_t pathlen;
788         const char *dpath = dirptr->smb_dname->base_name;
789         bool dirptr_path_is_dot = ISDOT(dpath);
790
791         *_smb_fname = NULL;
792         *_mode = 0;
793
794         pathlen = strlen(dpath);
795         slashlen = ( dpath[pathlen-1] != '/') ? 1 : 0;
796
797         while (true) {
798                 long cur_offset;
799                 long prev_offset;
800                 SMB_STRUCT_STAT sbuf = { 0 };
801                 char *dname = NULL;
802                 bool isdots;
803                 char *fname = NULL;
804                 char *pathreal = NULL;
805                 struct smb_filename smb_fname;
806                 uint32_t mode = 0;
807                 bool ok;
808
809                 cur_offset = dptr_TellDir(dirptr);
810                 prev_offset = cur_offset;
811                 dname = dptr_ReadDirName(ctx, dirptr, &cur_offset, &sbuf);
812
813                 DEBUG(6,("smbd_dirptr_get_entry: dirptr 0x%lx now at offset %ld\n",
814                         (long)dirptr, cur_offset));
815
816                 if (dname == NULL) {
817                         return false;
818                 }
819
820                 isdots = (ISDOT(dname) || ISDOTDOT(dname));
821                 if (dont_descend && !isdots) {
822                         TALLOC_FREE(dname);
823                         continue;
824                 }
825
826                 /*
827                  * fname may get mangled, dname is never mangled.
828                  * Whenever we're accessing the filesystem we use
829                  * pathreal which is composed from dname.
830                  */
831
832                 ok = match_fn(ctx, private_data, dname, mask, &fname);
833                 if (!ok) {
834                         TALLOC_FREE(dname);
835                         continue;
836                 }
837
838                 /*
839                  * This used to be
840                  * pathreal = talloc_asprintf(ctx, "%s%s%s", dirptr->path,
841                  *                            needslash?"/":"", dname);
842                  * but this was measurably slower than doing the memcpy.
843                  */
844
845                 pathreal = talloc_array(
846                         ctx, char,
847                         pathlen + slashlen + talloc_get_size(dname));
848                 if (!pathreal) {
849                         TALLOC_FREE(dname);
850                         TALLOC_FREE(fname);
851                         return false;
852                 }
853
854                 /*
855                  * We don't want to pass ./xxx to modules below us so don't
856                  * add the path if it is just . by itself.
857                  */
858                 if (dirptr_path_is_dot) {
859                         memcpy(pathreal, dname, talloc_get_size(dname));
860                 } else {
861                         memcpy(pathreal, dpath, pathlen);
862                         pathreal[pathlen] = '/';
863                         memcpy(pathreal + slashlen + pathlen, dname,
864                                talloc_get_size(dname));
865                 }
866
867                 /* Create smb_fname with NULL stream_name. */
868                 smb_fname = (struct smb_filename) {
869                         .base_name = pathreal, .st = sbuf
870                 };
871
872                 ok = mode_fn(ctx, private_data, &smb_fname, get_dosmode, &mode);
873                 if (!ok) {
874                         TALLOC_FREE(dname);
875                         TALLOC_FREE(fname);
876                         TALLOC_FREE(pathreal);
877                         continue;
878                 }
879
880                 if (!dir_check_ftype(mode, dirtype)) {
881                         DEBUG(5,("[%s] attribs 0x%x didn't match 0x%x\n",
882                                 fname, (unsigned int)mode, (unsigned int)dirtype));
883                         TALLOC_FREE(dname);
884                         TALLOC_FREE(fname);
885                         TALLOC_FREE(pathreal);
886                         continue;
887                 }
888
889                 if (ask_sharemode && !S_ISDIR(smb_fname.st.st_ex_mode)) {
890                         struct timespec write_time_ts;
891                         struct file_id fileid;
892
893                         fileid = vfs_file_id_from_sbuf(conn,
894                                                        &smb_fname.st);
895                         get_file_infos(fileid, 0, NULL, &write_time_ts);
896                         if (!is_omit_timespec(&write_time_ts)) {
897                                 update_stat_ex_mtime(&smb_fname.st,
898                                                      write_time_ts);
899                         }
900                 }
901
902                 DEBUG(3,("smbd_dirptr_get_entry mask=[%s] found %s "
903                         "fname=%s (%s)\n",
904                         mask, smb_fname_str_dbg(&smb_fname),
905                         dname, fname));
906
907                 if (!conn->sconn->using_smb2) {
908                         /*
909                          * The dircache is only needed for SMB1 because SMB1
910                          * uses a name for the resume wheras SMB2 always
911                          * continues from the next position (unless it's told to
912                          * restart or close-and-reopen the listing).
913                          */
914                         DirCacheAdd(dirptr->dir_hnd, dname, cur_offset);
915                 }
916
917                 TALLOC_FREE(dname);
918
919                 *_smb_fname = cp_smb_filename(ctx, &smb_fname);
920                 TALLOC_FREE(pathreal);
921                 if (*_smb_fname == NULL) {
922                         return false;
923                 }
924                 *_fname = fname;
925                 *_mode = mode;
926                 *_prev_offset = prev_offset;
927
928                 return true;
929         }
930
931         return false;
932 }
933
934 /****************************************************************************
935  Get an 8.3 directory entry.
936 ****************************************************************************/
937
938 static bool smbd_dirptr_8_3_match_fn(TALLOC_CTX *ctx,
939                                      void *private_data,
940                                      const char *dname,
941                                      const char *mask,
942                                      char **_fname)
943 {
944         connection_struct *conn = (connection_struct *)private_data;
945
946         if ((strcmp(mask,"*.*") == 0) ||
947             mask_match_search(dname, mask, false) ||
948             mangle_mask_match(conn, dname, mask)) {
949                 char mname[13];
950                 const char *fname;
951                 /*
952                  * Ensure we can push the original name as UCS2. If
953                  * not, then just don't return this name.
954                  */
955                 NTSTATUS status;
956                 size_t ret_len = 0;
957                 size_t len = (strlen(dname) + 2) * 4; /* Allow enough space. */
958                 uint8_t *tmp = talloc_array(talloc_tos(),
959                                         uint8_t,
960                                         len);
961
962                 status = srvstr_push(NULL,
963                         FLAGS2_UNICODE_STRINGS,
964                         tmp,
965                         dname,
966                         len,
967                         STR_TERMINATE,
968                         &ret_len);
969
970                 TALLOC_FREE(tmp);
971
972                 if (!NT_STATUS_IS_OK(status)) {
973                         return false;
974                 }
975
976                 if (!mangle_is_8_3(dname, false, conn->params)) {
977                         bool ok = name_to_8_3(dname, mname, false,
978                                               conn->params);
979                         if (!ok) {
980                                 return false;
981                         }
982                         fname = mname;
983                 } else {
984                         fname = dname;
985                 }
986
987                 *_fname = talloc_strdup(ctx, fname);
988                 if (*_fname == NULL) {
989                         return false;
990                 }
991
992                 return true;
993         }
994
995         return false;
996 }
997
998 static bool smbd_dirptr_8_3_mode_fn(TALLOC_CTX *ctx,
999                                     void *private_data,
1000                                     struct smb_filename *smb_fname,
1001                                     bool get_dosmode,
1002                                     uint32_t *_mode)
1003 {
1004         connection_struct *conn = (connection_struct *)private_data;
1005
1006         if (!VALID_STAT(smb_fname->st)) {
1007                 if ((SMB_VFS_STAT(conn, smb_fname)) != 0) {
1008                         DEBUG(5,("smbd_dirptr_8_3_mode_fn: "
1009                                  "Couldn't stat [%s]. Error "
1010                                  "= %s\n",
1011                                  smb_fname_str_dbg(smb_fname),
1012                                  strerror(errno)));
1013                         return false;
1014                 }
1015         }
1016
1017         *_mode = dos_mode(conn, smb_fname);
1018         return true;
1019 }
1020
1021 bool get_dir_entry(TALLOC_CTX *ctx,
1022                 struct dptr_struct *dirptr,
1023                 const char *mask,
1024                 uint32_t dirtype,
1025                 char **_fname,
1026                 off_t *_size,
1027                 uint32_t *_mode,
1028                 struct timespec *_date,
1029                 bool check_descend,
1030                 bool ask_sharemode)
1031 {
1032         connection_struct *conn = dirptr->conn;
1033         char *fname = NULL;
1034         struct smb_filename *smb_fname = NULL;
1035         uint32_t mode = 0;
1036         long prev_offset;
1037         bool ok;
1038
1039         ok = smbd_dirptr_get_entry(ctx,
1040                                    dirptr,
1041                                    mask,
1042                                    dirtype,
1043                                    check_descend,
1044                                    ask_sharemode,
1045                                    true,
1046                                    smbd_dirptr_8_3_match_fn,
1047                                    smbd_dirptr_8_3_mode_fn,
1048                                    conn,
1049                                    &fname,
1050                                    &smb_fname,
1051                                    &mode,
1052                                    &prev_offset);
1053         if (!ok) {
1054                 return false;
1055         }
1056
1057         *_fname = talloc_move(ctx, &fname);
1058         *_size = smb_fname->st.st_ex_size;
1059         *_mode = mode;
1060         *_date = smb_fname->st.st_ex_mtime;
1061         TALLOC_FREE(smb_fname);
1062         return true;
1063 }
1064
1065 /*******************************************************************
1066  Check to see if a user can read a file. This is only approximate,
1067  it is used as part of the "hide unreadable" option. Don't
1068  use it for anything security sensitive.
1069 ********************************************************************/
1070
1071 static bool user_can_read_file(connection_struct *conn,
1072                                 struct smb_filename *smb_fname)
1073 {
1074         NTSTATUS status;
1075         uint32_t rejected_share_access = 0;
1076         uint32_t rejected_mask = 0;
1077         struct security_descriptor *sd = NULL;
1078         uint32_t access_mask = FILE_READ_DATA|
1079                                 FILE_READ_EA|
1080                                 FILE_READ_ATTRIBUTES|
1081                                 SEC_STD_READ_CONTROL;
1082
1083         /*
1084          * Never hide files from the root user.
1085          * We use (uid_t)0 here not sec_initial_uid()
1086          * as make test uses a single user context.
1087          */
1088
1089         if (get_current_uid(conn) == (uid_t)0) {
1090                 return True;
1091         }
1092
1093         /*
1094          * We can't directly use smbd_check_access_rights()
1095          * here, as this implicitly grants FILE_READ_ATTRIBUTES
1096          * which the Windows access-based-enumeration code
1097          * explicitly checks for on the file security descriptor.
1098          * See bug:
1099          *
1100          * https://bugzilla.samba.org/show_bug.cgi?id=10252
1101          *
1102          * and the smb2.acl2.ACCESSBASED test for details.
1103          */
1104
1105         rejected_share_access = access_mask & ~(conn->share_access);
1106         if (rejected_share_access) {
1107                 DEBUG(10, ("rejected share access 0x%x "
1108                         "on %s (0x%x)\n",
1109                         (unsigned int)access_mask,
1110                         smb_fname_str_dbg(smb_fname),
1111                         (unsigned int)rejected_share_access ));
1112                 return false;
1113         }
1114
1115         status = SMB_VFS_GET_NT_ACL(conn,
1116                         smb_fname,
1117                         (SECINFO_OWNER |
1118                          SECINFO_GROUP |
1119                          SECINFO_DACL),
1120                         talloc_tos(),
1121                         &sd);
1122
1123         if (!NT_STATUS_IS_OK(status)) {
1124                 DEBUG(10, ("Could not get acl "
1125                         "on %s: %s\n",
1126                         smb_fname_str_dbg(smb_fname),
1127                         nt_errstr(status)));
1128                 return false;
1129         }
1130
1131         status = se_file_access_check(sd,
1132                                 get_current_nttok(conn),
1133                                 false,
1134                                 access_mask,
1135                                 &rejected_mask);
1136
1137         TALLOC_FREE(sd);
1138
1139         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
1140                 DEBUG(10,("rejected bits 0x%x read access for %s\n",
1141                         (unsigned int)rejected_mask,
1142                         smb_fname_str_dbg(smb_fname) ));
1143                 return false;
1144         }
1145         return true;
1146 }
1147
1148 /*******************************************************************
1149  Check to see if a user can write a file (and only files, we do not
1150  check dirs on this one). This is only approximate,
1151  it is used as part of the "hide unwriteable" option. Don't
1152  use it for anything security sensitive.
1153 ********************************************************************/
1154
1155 static bool user_can_write_file(connection_struct *conn,
1156                                 struct files_struct *dirfsp,
1157                                 const struct smb_filename *smb_fname)
1158 {
1159         SMB_ASSERT(dirfsp == conn->cwd_fsp);
1160
1161         /*
1162          * Never hide files from the root user.
1163          * We use (uid_t)0 here not sec_initial_uid()
1164          * as make test uses a single user context.
1165          */
1166
1167         if (get_current_uid(conn) == (uid_t)0) {
1168                 return True;
1169         }
1170
1171         SMB_ASSERT(VALID_STAT(smb_fname->st));
1172
1173         /* Pseudo-open the file */
1174
1175         if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1176                 return True;
1177         }
1178
1179         return can_write_to_file(conn, dirfsp, smb_fname);
1180 }
1181
1182 /*******************************************************************
1183   Is a file a "special" type ?
1184 ********************************************************************/
1185
1186 static bool file_is_special(connection_struct *conn,
1187                             const struct smb_filename *smb_fname)
1188 {
1189         /*
1190          * Never hide files from the root user.
1191          * We use (uid_t)0 here not sec_initial_uid()
1192          * as make test uses a single user context.
1193          */
1194
1195         if (get_current_uid(conn) == (uid_t)0) {
1196                 return False;
1197         }
1198
1199         SMB_ASSERT(VALID_STAT(smb_fname->st));
1200
1201         if (S_ISREG(smb_fname->st.st_ex_mode) ||
1202             S_ISDIR(smb_fname->st.st_ex_mode) ||
1203             S_ISLNK(smb_fname->st.st_ex_mode))
1204                 return False;
1205
1206         return True;
1207 }
1208
1209 /*******************************************************************
1210  Should the file be seen by the client?
1211  NOTE: A successful return is no guarantee of the file's existence.
1212 ********************************************************************/
1213
1214 bool is_visible_file(connection_struct *conn,
1215                 struct smb_Dir *dir_hnd,
1216                 const char *name,
1217                 SMB_STRUCT_STAT *pst,
1218                 bool use_veto)
1219 {
1220         bool hide_unreadable = lp_hide_unreadable(SNUM(conn));
1221         bool hide_unwriteable = lp_hide_unwriteable_files(SNUM(conn));
1222         bool hide_special = lp_hide_special_files(SNUM(conn));
1223         int hide_new_files_timeout = lp_hide_new_files_timeout(SNUM(conn));
1224         char *entry = NULL;
1225         struct smb_filename *dir_path = dir_hnd->fsp->fsp_name;
1226         struct smb_filename *smb_fname_base = NULL;
1227         bool ret = false;
1228
1229         if ((strcmp(".",name) == 0) || (strcmp("..",name) == 0)) {
1230                 return True; /* . and .. are always visible. */
1231         }
1232
1233         /* If it's a vetoed file, pretend it doesn't even exist */
1234         if (use_veto && IS_VETO_PATH(conn, name)) {
1235                 DEBUG(10,("is_visible_file: file %s is vetoed.\n", name ));
1236                 return False;
1237         }
1238
1239         if (hide_unreadable ||
1240             hide_unwriteable ||
1241             hide_special ||
1242             (hide_new_files_timeout != 0))
1243         {
1244                 entry = talloc_asprintf(talloc_tos(),
1245                                         "%s/%s",
1246                                         dir_path->base_name,
1247                                         name);
1248                 if (!entry) {
1249                         ret = false;
1250                         goto out;
1251                 }
1252
1253                 /* Create an smb_filename with stream_name == NULL. */
1254                 smb_fname_base = synthetic_smb_fname(talloc_tos(),
1255                                                 entry,
1256                                                 NULL,
1257                                                 pst,
1258                                                 0);
1259                 if (smb_fname_base == NULL) {
1260                         ret = false;
1261                         goto out;
1262                 }
1263
1264                 /* If the file name does not exist, there's no point checking
1265                  * the configuration options. We succeed, on the basis that the
1266                  * checks *might* have passed if the file was present.
1267                  */
1268                 if (!VALID_STAT(*pst)) {
1269                         if (SMB_VFS_STAT(conn, smb_fname_base) != 0) {
1270                                 ret = true;
1271                                 goto out;
1272                         }
1273                         *pst = smb_fname_base->st;
1274                 }
1275
1276                 /* Honour _hide unreadable_ option */
1277                 if (hide_unreadable &&
1278                     !user_can_read_file(conn,
1279                                 smb_fname_base))
1280                 {
1281                         DEBUG(10,("is_visible_file: file %s is unreadable.\n",
1282                                  entry ));
1283                         ret = false;
1284                         goto out;
1285                 }
1286                 /* Honour _hide unwriteable_ option */
1287                 if (hide_unwriteable &&
1288                     !user_can_write_file(conn,
1289                                 conn->cwd_fsp,
1290                                 smb_fname_base))
1291                 {
1292                         DEBUG(10,("is_visible_file: file %s is unwritable.\n",
1293                                  entry ));
1294                         ret = false;
1295                         goto out;
1296                 }
1297                 /* Honour _hide_special_ option */
1298                 if (hide_special && file_is_special(conn, smb_fname_base)) {
1299                         DEBUG(10,("is_visible_file: file %s is special.\n",
1300                                  entry ));
1301                         ret = false;
1302                         goto out;
1303                 }
1304
1305                 if (hide_new_files_timeout != 0) {
1306
1307                         double age = timespec_elapsed(
1308                                 &smb_fname_base->st.st_ex_mtime);
1309
1310                         if (age < (double)hide_new_files_timeout) {
1311                                 ret = false;
1312                                 goto out;
1313                         }
1314                 }
1315         }
1316
1317         ret = true;
1318  out:
1319         TALLOC_FREE(smb_fname_base);
1320         TALLOC_FREE(entry);
1321         return ret;
1322 }
1323
1324 static int smb_Dir_destructor(struct smb_Dir *dir_hnd)
1325 {
1326         files_struct *fsp = dir_hnd->fsp;
1327
1328         SMB_VFS_CLOSEDIR(dir_hnd->conn, dir_hnd->dir);
1329         fsp->fh->fd = -1;
1330         if (fsp->dptr != NULL) {
1331                 SMB_ASSERT(fsp->dptr->dir_hnd == dir_hnd);
1332                 fsp->dptr->dir_hnd = NULL;
1333         }
1334         dir_hnd->fsp = NULL;
1335         return 0;
1336 }
1337
1338 /*******************************************************************
1339  Open a directory.
1340 ********************************************************************/
1341
1342 static int smb_Dir_OpenDir_destructor(struct smb_Dir *dir_hnd)
1343 {
1344         files_struct *fsp = dir_hnd->fsp;
1345
1346         smb_Dir_destructor(dir_hnd);
1347         file_free(NULL, fsp);
1348         return 0;
1349 }
1350
1351 struct smb_Dir *OpenDir(TALLOC_CTX *mem_ctx,
1352                         connection_struct *conn,
1353                         const struct smb_filename *smb_dname,
1354                         const char *mask,
1355                         uint32_t attr)
1356 {
1357         struct files_struct *fsp = NULL;
1358         struct smb_Dir *dir_hnd = NULL;
1359         NTSTATUS status;
1360
1361         status = open_internal_dirfsp_at(conn, conn->cwd_fsp, smb_dname, &fsp);
1362         if (!NT_STATUS_IS_OK(status)) {
1363                 return NULL;
1364         }
1365
1366         dir_hnd = OpenDir_fsp(mem_ctx, conn, fsp, mask, attr);
1367         if (dir_hnd == NULL) {
1368                 return NULL;
1369         }
1370
1371         /*
1372          * This overwrites the destructor set by smb_Dir_OpenDir_destructor(),
1373          * but smb_Dir_OpenDir_destructor() calls the OpenDir_fsp() destructor.
1374          */
1375         talloc_set_destructor(dir_hnd, smb_Dir_OpenDir_destructor);
1376         return dir_hnd;
1377 }
1378
1379 /*******************************************************************
1380  Open a directory from an fsp.
1381 ********************************************************************/
1382
1383 static struct smb_Dir *OpenDir_fsp(TALLOC_CTX *mem_ctx, connection_struct *conn,
1384                         files_struct *fsp,
1385                         const char *mask,
1386                         uint32_t attr)
1387 {
1388         struct smb_Dir *dir_hnd = talloc_zero(mem_ctx, struct smb_Dir);
1389
1390         if (!dir_hnd) {
1391                 goto fail;
1392         }
1393
1394         if (!fsp->fsp_flags.is_directory) {
1395                 errno = EBADF;
1396                 goto fail;
1397         }
1398
1399         if (fsp->fh->fd == -1) {
1400                 errno = EBADF;
1401                 goto fail;
1402         }
1403
1404         dir_hnd->conn = conn;
1405
1406         if (!conn->sconn->using_smb2) {
1407                 /*
1408                  * The dircache is only needed for SMB1 because SMB1 uses a name
1409                  * for the resume wheras SMB2 always continues from the next
1410                  * position (unless it's told to restart or close-and-reopen the
1411                  * listing).
1412                  */
1413                 dir_hnd->name_cache_size =
1414                         lp_directory_name_cache_size(SNUM(conn));
1415         }
1416
1417         dir_hnd->dir_smb_fname = cp_smb_filename(dir_hnd, fsp->fsp_name);
1418         if (!dir_hnd->dir_smb_fname) {
1419                 errno = ENOMEM;
1420                 goto fail;
1421         }
1422
1423         dir_hnd->dir = SMB_VFS_FDOPENDIR(fsp, mask, attr);
1424         if (dir_hnd->dir == NULL) {
1425                 goto fail;
1426         }
1427         dir_hnd->fsp = fsp;
1428
1429         talloc_set_destructor(dir_hnd, smb_Dir_destructor);
1430
1431         return dir_hnd;
1432
1433   fail:
1434         TALLOC_FREE(dir_hnd);
1435         return NULL;
1436 }
1437
1438
1439 /*******************************************************************
1440  Read from a directory.
1441  Return directory entry, current offset, and optional stat information.
1442  Don't check for veto or invisible files.
1443 ********************************************************************/
1444
1445 const char *ReadDirName(struct smb_Dir *dir_hnd, long *poffset,
1446                         SMB_STRUCT_STAT *sbuf, char **ptalloced)
1447 {
1448         const char *n;
1449         char *talloced = NULL;
1450         connection_struct *conn = dir_hnd->conn;
1451
1452         /* Cheat to allow . and .. to be the first entries returned. */
1453         if (((*poffset == START_OF_DIRECTORY_OFFSET) ||
1454              (*poffset == DOT_DOT_DIRECTORY_OFFSET)) && (dir_hnd->file_number < 2))
1455         {
1456                 if (dir_hnd->file_number == 0) {
1457                         n = ".";
1458                         *poffset = dir_hnd->offset = START_OF_DIRECTORY_OFFSET;
1459                 } else {
1460                         n = "..";
1461                         *poffset = dir_hnd->offset = DOT_DOT_DIRECTORY_OFFSET;
1462                 }
1463                 dir_hnd->file_number++;
1464                 *ptalloced = NULL;
1465                 return n;
1466         }
1467
1468         if (*poffset == END_OF_DIRECTORY_OFFSET) {
1469                 *poffset = dir_hnd->offset = END_OF_DIRECTORY_OFFSET;
1470                 return NULL;
1471         }
1472
1473         /* A real offset, seek to it. */
1474         SeekDir(dir_hnd, *poffset);
1475
1476         while ((n = vfs_readdirname(conn, dir_hnd->dir, sbuf, &talloced))) {
1477                 /* Ignore . and .. - we've already returned them. */
1478                 if (*n == '.') {
1479                         if ((n[1] == '\0') || (n[1] == '.' && n[2] == '\0')) {
1480                                 TALLOC_FREE(talloced);
1481                                 continue;
1482                         }
1483                 }
1484                 *poffset = dir_hnd->offset = SMB_VFS_TELLDIR(conn, dir_hnd->dir);
1485                 *ptalloced = talloced;
1486                 dir_hnd->file_number++;
1487                 return n;
1488         }
1489         *poffset = dir_hnd->offset = END_OF_DIRECTORY_OFFSET;
1490         *ptalloced = NULL;
1491         return NULL;
1492 }
1493
1494 /*******************************************************************
1495  Rewind to the start.
1496 ********************************************************************/
1497
1498 void RewindDir(struct smb_Dir *dir_hnd, long *poffset)
1499 {
1500         SMB_VFS_REWINDDIR(dir_hnd->conn, dir_hnd->dir);
1501         dir_hnd->file_number = 0;
1502         dir_hnd->offset = START_OF_DIRECTORY_OFFSET;
1503         *poffset = START_OF_DIRECTORY_OFFSET;
1504 }
1505
1506 /*******************************************************************
1507  Seek a dir.
1508 ********************************************************************/
1509
1510 void SeekDir(struct smb_Dir *dirp, long offset)
1511 {
1512         if (offset != dirp->offset) {
1513                 if (offset == START_OF_DIRECTORY_OFFSET) {
1514                         RewindDir(dirp, &offset);
1515                         /*
1516                          * Ok we should really set the file number here
1517                          * to 1 to enable ".." to be returned next. Trouble
1518                          * is I'm worried about callers using SeekDir(dirp,0)
1519                          * as equivalent to RewindDir(). So leave this alone
1520                          * for now.
1521                          */
1522                 } else if  (offset == DOT_DOT_DIRECTORY_OFFSET) {
1523                         RewindDir(dirp, &offset);
1524                         /*
1525                          * Set the file number to 2 - we want to get the first
1526                          * real file entry (the one we return after "..")
1527                          * on the next ReadDir.
1528                          */
1529                         dirp->file_number = 2;
1530                 } else if (offset == END_OF_DIRECTORY_OFFSET) {
1531                         ; /* Don't seek in this case. */
1532                 } else {
1533                         SMB_VFS_SEEKDIR(dirp->conn, dirp->dir, offset);
1534                 }
1535                 dirp->offset = offset;
1536         }
1537 }
1538
1539 /*******************************************************************
1540  Tell a dir position.
1541 ********************************************************************/
1542
1543 long TellDir(struct smb_Dir *dir_hnd)
1544 {
1545         return(dir_hnd->offset);
1546 }
1547
1548 /*******************************************************************
1549  Add an entry into the dcache.
1550 ********************************************************************/
1551
1552 static void DirCacheAdd(struct smb_Dir *dir_hnd, const char *name, long offset)
1553 {
1554         struct name_cache_entry *e;
1555
1556         if (dir_hnd->name_cache_size == 0) {
1557                 return;
1558         }
1559
1560         if (dir_hnd->name_cache == NULL) {
1561                 dir_hnd->name_cache = talloc_zero_array(dir_hnd,
1562                                                 struct name_cache_entry,
1563                                                 dir_hnd->name_cache_size);
1564
1565                 if (dir_hnd->name_cache == NULL) {
1566                         return;
1567                 }
1568         }
1569
1570         dir_hnd->name_cache_index = (dir_hnd->name_cache_index+1) %
1571                                         dir_hnd->name_cache_size;
1572         e = &dir_hnd->name_cache[dir_hnd->name_cache_index];
1573         TALLOC_FREE(e->name);
1574         e->name = talloc_strdup(dir_hnd, name);
1575         e->offset = offset;
1576 }
1577
1578 /*******************************************************************
1579  Find an entry by name. Leave us at the offset after it.
1580  Don't check for veto or invisible files.
1581 ********************************************************************/
1582
1583 bool SearchDir(struct smb_Dir *dir_hnd, const char *name, long *poffset)
1584 {
1585         int i;
1586         const char *entry = NULL;
1587         char *talloced = NULL;
1588         connection_struct *conn = dir_hnd->conn;
1589
1590         /* Search back in the name cache. */
1591         if (dir_hnd->name_cache_size && dir_hnd->name_cache) {
1592                 for (i = dir_hnd->name_cache_index; i >= 0; i--) {
1593                         struct name_cache_entry *e = &dir_hnd->name_cache[i];
1594                         if (e->name && (conn->case_sensitive ? (strcmp(e->name, name) == 0) : strequal(e->name, name))) {
1595                                 *poffset = e->offset;
1596                                 SeekDir(dir_hnd, e->offset);
1597                                 return True;
1598                         }
1599                 }
1600                 for (i = dir_hnd->name_cache_size - 1;
1601                                 i > dir_hnd->name_cache_index; i--) {
1602                         struct name_cache_entry *e = &dir_hnd->name_cache[i];
1603                         if (e->name && (conn->case_sensitive ? (strcmp(e->name, name) == 0) : strequal(e->name, name))) {
1604                                 *poffset = e->offset;
1605                                 SeekDir(dir_hnd, e->offset);
1606                                 return True;
1607                         }
1608                 }
1609         }
1610
1611         /* Not found in the name cache. Rewind directory and start from scratch. */
1612         SMB_VFS_REWINDDIR(conn, dir_hnd->dir);
1613         dir_hnd->file_number = 0;
1614         *poffset = START_OF_DIRECTORY_OFFSET;
1615         while ((entry = ReadDirName(dir_hnd, poffset, NULL, &talloced))) {
1616                 if (conn->case_sensitive ? (strcmp(entry, name) == 0) : strequal(entry, name)) {
1617                         TALLOC_FREE(talloced);
1618                         return True;
1619                 }
1620                 TALLOC_FREE(talloced);
1621         }
1622         return False;
1623 }
1624
1625 struct files_below_forall_state {
1626         char *dirpath;
1627         size_t dirpath_len;
1628         int (*fn)(struct file_id fid, const struct share_mode_data *data,
1629                   void *private_data);
1630         void *private_data;
1631 };
1632
1633 static int files_below_forall_fn(struct file_id fid,
1634                                  const struct share_mode_data *data,
1635                                  void *private_data)
1636 {
1637         struct files_below_forall_state *state = private_data;
1638         char tmpbuf[PATH_MAX];
1639         char *fullpath, *to_free;
1640         size_t len;
1641
1642         len = full_path_tos(data->servicepath, data->base_name,
1643                             tmpbuf, sizeof(tmpbuf),
1644                             &fullpath, &to_free);
1645         if (len == -1) {
1646                 return 0;
1647         }
1648         if (state->dirpath_len >= len) {
1649                 /*
1650                  * Filter files above dirpath
1651                  */
1652                 goto out;
1653         }
1654         if (fullpath[state->dirpath_len] != '/') {
1655                 /*
1656                  * Filter file that don't have a path separator at the end of
1657                  * dirpath's length
1658                  */
1659                 goto out;
1660         }
1661
1662         if (memcmp(state->dirpath, fullpath, state->dirpath_len) != 0) {
1663                 /*
1664                  * Not a parent
1665                  */
1666                 goto out;
1667         }
1668
1669         TALLOC_FREE(to_free);
1670         return state->fn(fid, data, state->private_data);
1671
1672 out:
1673         TALLOC_FREE(to_free);
1674         return 0;
1675 }
1676
1677 static int files_below_forall(connection_struct *conn,
1678                               const struct smb_filename *dir_name,
1679                               int (*fn)(struct file_id fid,
1680                                         const struct share_mode_data *data,
1681                                         void *private_data),
1682                               void *private_data)
1683 {
1684         struct files_below_forall_state state = {
1685                         .fn = fn,
1686                         .private_data = private_data,
1687         };
1688         int ret;
1689         char tmpbuf[PATH_MAX];
1690         char *to_free;
1691
1692         state.dirpath_len = full_path_tos(conn->connectpath,
1693                                           dir_name->base_name,
1694                                           tmpbuf, sizeof(tmpbuf),
1695                                           &state.dirpath, &to_free);
1696         if (state.dirpath_len == -1) {
1697                 return -1;
1698         }
1699
1700         ret = share_mode_forall(files_below_forall_fn, &state);
1701         TALLOC_FREE(to_free);
1702         return ret;
1703 }
1704
1705 struct have_file_open_below_state {
1706         bool found_one;
1707 };
1708
1709 static int have_file_open_below_fn(struct file_id fid,
1710                                    const struct share_mode_data *data,
1711                                    void *private_data)
1712 {
1713         struct have_file_open_below_state *state = private_data;
1714         state->found_one = true;
1715         return 1;
1716 }
1717
1718 bool have_file_open_below(connection_struct *conn,
1719                                  const struct smb_filename *name)
1720 {
1721         struct have_file_open_below_state state = {
1722                 .found_one = false,
1723         };
1724         int ret;
1725
1726         if (!VALID_STAT(name->st)) {
1727                 return false;
1728         }
1729         if (!S_ISDIR(name->st.st_ex_mode)) {
1730                 return false;
1731         }
1732
1733         ret = files_below_forall(conn, name, have_file_open_below_fn, &state);
1734         if (ret == -1) {
1735                 return false;
1736         }
1737
1738         return state.found_one;
1739 }
1740
1741 /*****************************************************************
1742  Is this directory empty ?
1743 *****************************************************************/
1744
1745 NTSTATUS can_delete_directory_fsp(files_struct *fsp)
1746 {
1747         NTSTATUS status = NT_STATUS_OK;
1748         long dirpos = 0;
1749         const char *dname = NULL;
1750         char *talloced = NULL;
1751         SMB_STRUCT_STAT st;
1752         struct connection_struct *conn = fsp->conn;
1753         struct smb_Dir *dir_hnd = OpenDir(talloc_tos(),
1754                                         conn,
1755                                         fsp->fsp_name,
1756                                         NULL,
1757                                         0);
1758
1759         if (!dir_hnd) {
1760                 return map_nt_error_from_unix(errno);
1761         }
1762
1763         while ((dname = ReadDirName(dir_hnd, &dirpos, &st, &talloced))) {
1764                 /* Quick check for "." and ".." */
1765                 if (dname[0] == '.') {
1766                         if (!dname[1] || (dname[1] == '.' && !dname[2])) {
1767                                 TALLOC_FREE(talloced);
1768                                 continue;
1769                         }
1770                 }
1771
1772                 if (!is_visible_file(conn,
1773                                 dir_hnd,
1774                                 dname,
1775                                 &st,
1776                                 True)) {
1777                         TALLOC_FREE(talloced);
1778                         continue;
1779                 }
1780
1781                 DEBUG(10,("got name %s - can't delete\n",
1782                          dname ));
1783                 status = NT_STATUS_DIRECTORY_NOT_EMPTY;
1784                 break;
1785         }
1786         TALLOC_FREE(talloced);
1787         TALLOC_FREE(dir_hnd);
1788
1789         if (!NT_STATUS_IS_OK(status)) {
1790                 return status;
1791         }
1792
1793         if (!(fsp->posix_flags & FSP_POSIX_FLAGS_RENAME) &&
1794             lp_strict_rename(SNUM(conn)) &&
1795             have_file_open_below(fsp->conn, fsp->fsp_name))
1796         {
1797                 return NT_STATUS_ACCESS_DENIED;
1798         }
1799
1800         return NT_STATUS_OK;
1801 }