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