1e2c02e12d5f574843233b09eaa1d6fbe93d4720
[sfrench/samba-autobuild/.git] / source3 / smbd / trans2.c
1 /*
2    Unix SMB/CIFS implementation.
3    SMB transaction2 handling
4    Copyright (C) Jeremy Allison                 1994-2007
5    Copyright (C) Stefan (metze) Metzmacher      2003
6    Copyright (C) Volker Lendecke                2005-2007
7    Copyright (C) Steve French                   2005
8    Copyright (C) James Peach                    2006-2007
9
10    Extensively modified by Andrew Tridgell, 1995
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3 of the License, or
15    (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #include "includes.h"
27 #include "ntioctl.h"
28 #include "system/filesys.h"
29 #include "version.h"
30 #include "smbd/smbd.h"
31 #include "smbd/globals.h"
32 #include "../libcli/auth/libcli_auth.h"
33 #include "../librpc/gen_ndr/xattr.h"
34 #include "../librpc/gen_ndr/ndr_security.h"
35 #include "../librpc/gen_ndr/open_files.h"
36 #include "libcli/security/security.h"
37 #include "trans2.h"
38 #include "auth.h"
39 #include "smbprofile.h"
40 #include "rpc_server/srv_pipe_hnd.h"
41 #include "printing.h"
42 #include "lib/util_ea.h"
43
44 #define DIR_ENTRY_SAFETY_MARGIN 4096
45
46 static char *store_file_unix_basic(connection_struct *conn,
47                                 char *pdata,
48                                 files_struct *fsp,
49                                 const SMB_STRUCT_STAT *psbuf);
50
51 static char *store_file_unix_basic_info2(connection_struct *conn,
52                                 char *pdata,
53                                 files_struct *fsp,
54                                 const SMB_STRUCT_STAT *psbuf);
55
56 /********************************************************************
57  The canonical "check access" based on object handle or path function.
58 ********************************************************************/
59
60 NTSTATUS check_access(connection_struct *conn,
61                                 files_struct *fsp,
62                                 const struct smb_filename *smb_fname,
63                                 uint32_t access_mask)
64 {
65         if (fsp) {
66                 if (!(fsp->access_mask & access_mask)) {
67                         return NT_STATUS_ACCESS_DENIED;
68                 }
69         } else {
70                 NTSTATUS status = smbd_check_access_rights(conn,
71                                         smb_fname,
72                                         false,
73                                         access_mask);
74                 if (!NT_STATUS_IS_OK(status)) {
75                         return status;
76                 }
77         }
78         return NT_STATUS_OK;
79 }
80
81 /********************************************************************
82  Roundup a value to the nearest allocation roundup size boundary.
83  Only do this for Windows clients.
84 ********************************************************************/
85
86 uint64_t smb_roundup(connection_struct *conn, uint64_t val)
87 {
88         uint64_t rval = lp_allocation_roundup_size(SNUM(conn));
89
90         /* Only roundup for Windows clients. */
91         enum remote_arch_types ra_type = get_remote_arch();
92         if (rval && (ra_type != RA_SAMBA) && (ra_type != RA_CIFSFS)) {
93                 val = SMB_ROUNDUP(val,rval);
94         }
95         return val;
96 }
97
98 /********************************************************************
99  Create a 64 bit FileIndex. If the file is on the same device as
100  the root of the share, just return the 64-bit inode. If it isn't,
101  mangle as we used to do.
102 ********************************************************************/
103
104 uint64_t get_FileIndex(connection_struct *conn, const SMB_STRUCT_STAT *psbuf)
105 {
106         uint64_t file_index;
107         if (conn->base_share_dev == psbuf->st_ex_dev) {
108                 return (uint64_t)psbuf->st_ex_ino;
109         }
110         file_index = ((psbuf->st_ex_ino) & UINT32_MAX); /* FileIndexLow */
111         file_index |= ((uint64_t)((psbuf->st_ex_dev) & UINT32_MAX)) << 32; /* FileIndexHigh */
112         return file_index;
113 }
114
115 /****************************************************************************
116  Utility functions for dealing with extended attributes.
117 ****************************************************************************/
118
119 /****************************************************************************
120  Refuse to allow clients to overwrite our private xattrs.
121 ****************************************************************************/
122
123 bool samba_private_attr_name(const char *unix_ea_name)
124 {
125         static const char * const prohibited_ea_names[] = {
126                 SAMBA_POSIX_INHERITANCE_EA_NAME,
127                 SAMBA_XATTR_DOS_ATTRIB,
128                 SAMBA_XATTR_MARKER,
129                 XATTR_NTACL_NAME,
130                 NULL
131         };
132
133         int i;
134
135         for (i = 0; prohibited_ea_names[i]; i++) {
136                 if (strequal( prohibited_ea_names[i], unix_ea_name))
137                         return true;
138         }
139         if (strncasecmp_m(unix_ea_name, SAMBA_XATTR_DOSSTREAM_PREFIX,
140                         strlen(SAMBA_XATTR_DOSSTREAM_PREFIX)) == 0) {
141                 return true;
142         }
143         return false;
144 }
145
146 /****************************************************************************
147  Get one EA value. Fill in a struct ea_struct.
148 ****************************************************************************/
149
150 NTSTATUS get_ea_value(TALLOC_CTX *mem_ctx, connection_struct *conn,
151                       files_struct *fsp, const char *fname,
152                       const char *ea_name, struct ea_struct *pea)
153 {
154         /* Get the value of this xattr. Max size is 64k. */
155         size_t attr_size = 256;
156         char *val = NULL;
157         ssize_t sizeret;
158
159  again:
160
161         val = talloc_realloc(mem_ctx, val, char, attr_size);
162         if (!val) {
163                 return NT_STATUS_NO_MEMORY;
164         }
165
166         if (fsp && fsp->fh->fd != -1) {
167                 sizeret = SMB_VFS_FGETXATTR(fsp, ea_name, val, attr_size);
168         } else {
169                 sizeret = SMB_VFS_GETXATTR(conn, fname, ea_name, val, attr_size);
170         }
171
172         if (sizeret == -1 && errno == ERANGE && attr_size != 65536) {
173                 attr_size = 65536;
174                 goto again;
175         }
176
177         if (sizeret == -1) {
178                 return map_nt_error_from_unix(errno);
179         }
180
181         DEBUG(10,("get_ea_value: EA %s is of length %u\n", ea_name, (unsigned int)sizeret));
182         dump_data(10, (uint8 *)val, sizeret);
183
184         pea->flags = 0;
185         if (strnequal(ea_name, "user.", 5)) {
186                 pea->name = talloc_strdup(mem_ctx, &ea_name[5]);
187         } else {
188                 pea->name = talloc_strdup(mem_ctx, ea_name);
189         }
190         if (pea->name == NULL) {
191                 TALLOC_FREE(val);
192                 return NT_STATUS_NO_MEMORY;
193         }
194         pea->value.data = (unsigned char *)val;
195         pea->value.length = (size_t)sizeret;
196         return NT_STATUS_OK;
197 }
198
199 NTSTATUS get_ea_names_from_file(TALLOC_CTX *mem_ctx, connection_struct *conn,
200                                 files_struct *fsp, const char *fname,
201                                 char ***pnames, size_t *pnum_names)
202 {
203         /* Get a list of all xattrs. Max namesize is 64k. */
204         size_t ea_namelist_size = 1024;
205         char *ea_namelist = NULL;
206
207         char *p;
208         char **names, **tmp;
209         size_t num_names;
210         ssize_t sizeret = -1;
211
212         if (!lp_ea_support(SNUM(conn))) {
213                 if (pnames) {
214                         *pnames = NULL;
215                 }
216                 *pnum_names = 0;
217                 return NT_STATUS_OK;
218         }
219
220         /*
221          * TALLOC the result early to get the talloc hierarchy right.
222          */
223
224         names = talloc_array(mem_ctx, char *, 1);
225         if (names == NULL) {
226                 DEBUG(0, ("talloc failed\n"));
227                 return NT_STATUS_NO_MEMORY;
228         }
229
230         while (ea_namelist_size <= 65536) {
231
232                 ea_namelist = talloc_realloc(
233                         names, ea_namelist, char, ea_namelist_size);
234                 if (ea_namelist == NULL) {
235                         DEBUG(0, ("talloc failed\n"));
236                         TALLOC_FREE(names);
237                         return NT_STATUS_NO_MEMORY;
238                 }
239
240                 if (fsp && fsp->fh->fd != -1) {
241                         sizeret = SMB_VFS_FLISTXATTR(fsp, ea_namelist,
242                                                      ea_namelist_size);
243                 } else {
244                         sizeret = SMB_VFS_LISTXATTR(conn, fname, ea_namelist,
245                                                     ea_namelist_size);
246                 }
247
248                 if ((sizeret == -1) && (errno == ERANGE)) {
249                         ea_namelist_size *= 2;
250                 }
251                 else {
252                         break;
253                 }
254         }
255
256         if (sizeret == -1) {
257                 TALLOC_FREE(names);
258                 return map_nt_error_from_unix(errno);
259         }
260
261         DEBUG(10, ("%s: ea_namelist size = %u\n",
262                    __func__, (unsigned int)sizeret));
263
264         if (sizeret == 0) {
265                 TALLOC_FREE(names);
266                 if (pnames) {
267                         *pnames = NULL;
268                 }
269                 *pnum_names = 0;
270                 return NT_STATUS_OK;
271         }
272
273         /*
274          * Ensure the result is 0-terminated
275          */
276
277         if (ea_namelist[sizeret-1] != '\0') {
278                 TALLOC_FREE(names);
279                 return NT_STATUS_INTERNAL_ERROR;
280         }
281
282         /*
283          * count the names
284          */
285         num_names = 0;
286
287         for (p = ea_namelist; p - ea_namelist < sizeret; p += strlen(p)+1) {
288                 num_names += 1;
289         }
290
291         tmp = talloc_realloc(mem_ctx, names, char *, num_names);
292         if (tmp == NULL) {
293                 DEBUG(0, ("talloc failed\n"));
294                 TALLOC_FREE(names);
295                 return NT_STATUS_NO_MEMORY;
296         }
297
298         names = tmp;
299         num_names = 0;
300
301         for (p = ea_namelist; p - ea_namelist < sizeret; p += strlen(p)+1) {
302                 names[num_names++] = p;
303         }
304
305         if (pnames) {
306                 *pnames = names;
307         } else {
308                 TALLOC_FREE(names);
309         }
310         *pnum_names = num_names;
311         return NT_STATUS_OK;
312 }
313
314 /****************************************************************************
315  Return a linked list of the total EA's. Plus the total size
316 ****************************************************************************/
317
318 static NTSTATUS get_ea_list_from_file_path(TALLOC_CTX *mem_ctx, connection_struct *conn, files_struct *fsp,
319                                       const char *fname, size_t *pea_total_len, struct ea_list **ea_list)
320 {
321         /* Get a list of all xattrs. Max namesize is 64k. */
322         size_t i, num_names;
323         char **names;
324         struct ea_list *ea_list_head = NULL;
325         NTSTATUS status;
326
327         *pea_total_len = 0;
328         *ea_list = NULL;
329
330         status = get_ea_names_from_file(talloc_tos(), conn, fsp, fname,
331                                         &names, &num_names);
332
333         if (!NT_STATUS_IS_OK(status)) {
334                 return status;
335         }
336
337         if (num_names == 0) {
338                 *ea_list = NULL;
339                 return NT_STATUS_OK;
340         }
341
342         for (i=0; i<num_names; i++) {
343                 struct ea_list *listp;
344                 fstring dos_ea_name;
345
346                 if (strnequal(names[i], "system.", 7)
347                     || samba_private_attr_name(names[i]))
348                         continue;
349
350                 /*
351                  * Filter out any underlying POSIX EA names
352                  * that a Windows client can't handle.
353                  */
354                 if (!lp_posix_pathnames() &&
355                                 is_invalid_windows_ea_name(names[i])) {
356                         continue;
357                 }
358
359                 listp = talloc(mem_ctx, struct ea_list);
360                 if (listp == NULL) {
361                         return NT_STATUS_NO_MEMORY;
362                 }
363
364                 status = get_ea_value(listp, conn, fsp,
365                                       fname, names[i],
366                                       &listp->ea);
367
368                 if (!NT_STATUS_IS_OK(status)) {
369                         TALLOC_FREE(listp);
370                         return status;
371                 }
372
373                 if (listp->ea.value.length == 0) {
374                         /*
375                          * We can never return a zero length EA.
376                          * Windows reports the EA's as corrupted.
377                          */
378                         TALLOC_FREE(listp);
379                         continue;
380                 }
381
382                 push_ascii_fstring(dos_ea_name, listp->ea.name);
383
384                 *pea_total_len +=
385                         4 + strlen(dos_ea_name) + 1 + listp->ea.value.length;
386
387                 DEBUG(10,("get_ea_list_from_file: total_len = %u, %s, val len "
388                           "= %u\n", (unsigned int)*pea_total_len, dos_ea_name,
389                           (unsigned int)listp->ea.value.length));
390
391                 DLIST_ADD_END(ea_list_head, listp, struct ea_list *);
392
393         }
394
395         /* Add on 4 for total length. */
396         if (*pea_total_len) {
397                 *pea_total_len += 4;
398         }
399
400         DEBUG(10, ("get_ea_list_from_file: total_len = %u\n",
401                    (unsigned int)*pea_total_len));
402
403         *ea_list = ea_list_head;
404         return NT_STATUS_OK;
405 }
406
407 static NTSTATUS get_ea_list_from_file(TALLOC_CTX *mem_ctx, connection_struct *conn, files_struct *fsp,
408                                       const struct smb_filename *smb_fname, size_t *pea_total_len, struct ea_list **ea_list)
409 {
410         *pea_total_len = 0;
411         *ea_list = NULL;
412
413         if (!lp_ea_support(SNUM(conn))) {
414                 return NT_STATUS_OK;
415         }
416
417         if (is_ntfs_stream_smb_fname(smb_fname)) {
418                 return NT_STATUS_INVALID_PARAMETER;
419         }
420
421         return get_ea_list_from_file_path(mem_ctx, conn, fsp, smb_fname->base_name, pea_total_len, ea_list);
422 }
423
424 /****************************************************************************
425  Fill a qfilepathinfo buffer with EA's. Returns the length of the buffer
426  that was filled.
427 ****************************************************************************/
428
429 static unsigned int fill_ea_buffer(TALLOC_CTX *mem_ctx, char *pdata, unsigned int total_data_size,
430         connection_struct *conn, struct ea_list *ea_list)
431 {
432         unsigned int ret_data_size = 4;
433         char *p = pdata;
434
435         SMB_ASSERT(total_data_size >= 4);
436
437         if (!lp_ea_support(SNUM(conn))) {
438                 SIVAL(pdata,4,0);
439                 return 4;
440         }
441
442         for (p = pdata + 4; ea_list; ea_list = ea_list->next) {
443                 size_t dos_namelen;
444                 fstring dos_ea_name;
445                 push_ascii_fstring(dos_ea_name, ea_list->ea.name);
446                 dos_namelen = strlen(dos_ea_name);
447                 if (dos_namelen > 255 || dos_namelen == 0) {
448                         break;
449                 }
450                 if (ea_list->ea.value.length > 65535) {
451                         break;
452                 }
453                 if (4 + dos_namelen + 1 + ea_list->ea.value.length > total_data_size) {
454                         break;
455                 }
456
457                 /* We know we have room. */
458                 SCVAL(p,0,ea_list->ea.flags);
459                 SCVAL(p,1,dos_namelen);
460                 SSVAL(p,2,ea_list->ea.value.length);
461                 strlcpy(p+4, dos_ea_name, dos_namelen+1);
462                 memcpy( p + 4 + dos_namelen + 1, ea_list->ea.value.data, ea_list->ea.value.length);
463
464                 total_data_size -= 4 + dos_namelen + 1 + ea_list->ea.value.length;
465                 p += 4 + dos_namelen + 1 + ea_list->ea.value.length;
466         }
467
468         ret_data_size = PTR_DIFF(p, pdata);
469         DEBUG(10,("fill_ea_buffer: data_size = %u\n", ret_data_size ));
470         SIVAL(pdata,0,ret_data_size);
471         return ret_data_size;
472 }
473
474 static NTSTATUS fill_ea_chained_buffer(TALLOC_CTX *mem_ctx,
475                                        char *pdata,
476                                        unsigned int total_data_size,
477                                        unsigned int *ret_data_size,
478                                        connection_struct *conn,
479                                        struct ea_list *ea_list)
480 {
481         uint8_t *p = (uint8_t *)pdata;
482         uint8_t *last_start = NULL;
483         bool do_store_data = (pdata != NULL);
484
485         *ret_data_size = 0;
486
487         if (!lp_ea_support(SNUM(conn))) {
488                 return NT_STATUS_NO_EAS_ON_FILE;
489         }
490
491         for (; ea_list; ea_list = ea_list->next) {
492                 size_t dos_namelen;
493                 fstring dos_ea_name;
494                 size_t this_size;
495                 size_t pad = 0;
496
497                 if (last_start != NULL && do_store_data) {
498                         SIVAL(last_start, 0, PTR_DIFF(p, last_start));
499                 }
500                 last_start = p;
501
502                 push_ascii_fstring(dos_ea_name, ea_list->ea.name);
503                 dos_namelen = strlen(dos_ea_name);
504                 if (dos_namelen > 255 || dos_namelen == 0) {
505                         return NT_STATUS_INTERNAL_ERROR;
506                 }
507                 if (ea_list->ea.value.length > 65535) {
508                         return NT_STATUS_INTERNAL_ERROR;
509                 }
510
511                 this_size = 0x08 + dos_namelen + 1 + ea_list->ea.value.length;
512
513                 if (ea_list->next) {
514                         pad = (4 - (this_size % 4)) % 4;
515                         this_size += pad;
516                 }
517
518                 if (do_store_data) {
519                         if (this_size > total_data_size) {
520                                 return NT_STATUS_INFO_LENGTH_MISMATCH;
521                         }
522
523                         /* We know we have room. */
524                         SIVAL(p, 0x00, 0); /* next offset */
525                         SCVAL(p, 0x04, ea_list->ea.flags);
526                         SCVAL(p, 0x05, dos_namelen);
527                         SSVAL(p, 0x06, ea_list->ea.value.length);
528                         strlcpy((char *)(p+0x08), dos_ea_name, dos_namelen+1);
529                         memcpy(p + 0x08 + dos_namelen + 1, ea_list->ea.value.data, ea_list->ea.value.length);
530                         if (pad) {
531                                 memset(p + 0x08 + dos_namelen + 1 + ea_list->ea.value.length,
532                                         '\0',
533                                         pad);
534                         }
535                         total_data_size -= this_size;
536                 }
537
538                 p += this_size;
539         }
540
541         *ret_data_size = PTR_DIFF(p, pdata);
542         DEBUG(10,("fill_ea_chained_buffer: data_size = %u\n", *ret_data_size));
543         return NT_STATUS_OK;
544 }
545
546 static unsigned int estimate_ea_size(connection_struct *conn, files_struct *fsp, const struct smb_filename *smb_fname)
547 {
548         size_t total_ea_len = 0;
549         TALLOC_CTX *mem_ctx;
550         struct ea_list *ea_list = NULL;
551
552         if (!lp_ea_support(SNUM(conn))) {
553                 return 0;
554         }
555         mem_ctx = talloc_stackframe();
556
557         /* If this is a stream fsp, then we need to instead find the
558          * estimated ea len from the main file, not the stream
559          * (streams cannot have EAs), but the estimate isn't just 0 in
560          * this case! */
561         if (is_ntfs_stream_smb_fname(smb_fname)) {
562                 fsp = NULL;
563         }
564         (void)get_ea_list_from_file_path(mem_ctx, conn, fsp, smb_fname->base_name, &total_ea_len, &ea_list);
565         if(conn->sconn->using_smb2) {
566                 NTSTATUS status;
567                 unsigned int ret_data_size;
568                 /*
569                  * We're going to be using fill_ea_chained_buffer() to
570                  * marshall EA's - this size is significantly larger
571                  * than the SMB1 buffer. Re-calculate the size without
572                  * marshalling.
573                  */
574                 status = fill_ea_chained_buffer(mem_ctx,
575                                                 NULL,
576                                                 0,
577                                                 &ret_data_size,
578                                                 conn,
579                                                 ea_list);
580                 if (!NT_STATUS_IS_OK(status)) {
581                         ret_data_size = 0;
582                 }
583                 total_ea_len = ret_data_size;
584         }
585         TALLOC_FREE(mem_ctx);
586         return total_ea_len;
587 }
588
589 /****************************************************************************
590  Ensure the EA name is case insensitive by matching any existing EA name.
591 ****************************************************************************/
592
593 static void canonicalize_ea_name(connection_struct *conn, files_struct *fsp, const char *fname, fstring unix_ea_name)
594 {
595         size_t total_ea_len;
596         TALLOC_CTX *mem_ctx = talloc_tos();
597         struct ea_list *ea_list;
598         NTSTATUS status = get_ea_list_from_file_path(mem_ctx, conn, fsp, fname, &total_ea_len, &ea_list);
599         if (!NT_STATUS_IS_OK(status)) {
600                 return;
601         }
602
603         for (; ea_list; ea_list = ea_list->next) {
604                 if (strequal(&unix_ea_name[5], ea_list->ea.name)) {
605                         DEBUG(10,("canonicalize_ea_name: %s -> %s\n",
606                                 &unix_ea_name[5], ea_list->ea.name));
607                         strlcpy(&unix_ea_name[5], ea_list->ea.name, sizeof(fstring)-5);
608                         break;
609                 }
610         }
611 }
612
613 /****************************************************************************
614  Set or delete an extended attribute.
615 ****************************************************************************/
616
617 NTSTATUS set_ea(connection_struct *conn, files_struct *fsp,
618                 const struct smb_filename *smb_fname, struct ea_list *ea_list)
619 {
620         NTSTATUS status;
621         char *fname = NULL;
622
623         if (!lp_ea_support(SNUM(conn))) {
624                 return NT_STATUS_EAS_NOT_SUPPORTED;
625         }
626
627         status = check_access(conn, fsp, smb_fname, FILE_WRITE_EA);
628         if (!NT_STATUS_IS_OK(status)) {
629                 return status;
630         }
631
632         /* Setting EAs on streams isn't supported. */
633         if (is_ntfs_stream_smb_fname(smb_fname)) {
634                 return NT_STATUS_INVALID_PARAMETER;
635         }
636
637         /*
638          * Filter out invalid Windows EA names - before
639          * we set *any* of them.
640          */
641
642         if (ea_list_has_invalid_name(ea_list)) {
643                 return STATUS_INVALID_EA_NAME;
644         }
645
646         fname = smb_fname->base_name;
647
648         for (;ea_list; ea_list = ea_list->next) {
649                 int ret;
650                 fstring unix_ea_name;
651
652                 fstrcpy(unix_ea_name, "user."); /* All EA's must start with user. */
653                 fstrcat(unix_ea_name, ea_list->ea.name);
654
655                 canonicalize_ea_name(conn, fsp, fname, unix_ea_name);
656
657                 DEBUG(10,("set_ea: ea_name %s ealen = %u\n", unix_ea_name, (unsigned int)ea_list->ea.value.length));
658
659                 if (samba_private_attr_name(unix_ea_name)) {
660                         DEBUG(10,("set_ea: ea name %s is a private Samba name.\n", unix_ea_name));
661                         return NT_STATUS_ACCESS_DENIED;
662                 }
663
664                 if (ea_list->ea.value.length == 0) {
665                         /* Remove the attribute. */
666                         if (fsp && (fsp->fh->fd != -1)) {
667                                 DEBUG(10,("set_ea: deleting ea name %s on "
668                                           "file %s by file descriptor.\n",
669                                           unix_ea_name, fsp_str_dbg(fsp)));
670                                 ret = SMB_VFS_FREMOVEXATTR(fsp, unix_ea_name);
671                         } else {
672                                 DEBUG(10,("set_ea: deleting ea name %s on file %s.\n",
673                                         unix_ea_name, fname));
674                                 ret = SMB_VFS_REMOVEXATTR(conn, fname, unix_ea_name);
675                         }
676 #ifdef ENOATTR
677                         /* Removing a non existent attribute always succeeds. */
678                         if (ret == -1 && errno == ENOATTR) {
679                                 DEBUG(10,("set_ea: deleting ea name %s didn't exist - succeeding by default.\n",
680                                                 unix_ea_name));
681                                 ret = 0;
682                         }
683 #endif
684                 } else {
685                         if (fsp && (fsp->fh->fd != -1)) {
686                                 DEBUG(10,("set_ea: setting ea name %s on file "
687                                           "%s by file descriptor.\n",
688                                           unix_ea_name, fsp_str_dbg(fsp)));
689                                 ret = SMB_VFS_FSETXATTR(fsp, unix_ea_name,
690                                                         ea_list->ea.value.data, ea_list->ea.value.length, 0);
691                         } else {
692                                 DEBUG(10,("set_ea: setting ea name %s on file %s.\n",
693                                         unix_ea_name, fname));
694                                 ret = SMB_VFS_SETXATTR(conn, fname, unix_ea_name,
695                                                         ea_list->ea.value.data, ea_list->ea.value.length, 0);
696                         }
697                 }
698
699                 if (ret == -1) {
700 #ifdef ENOTSUP
701                         if (errno == ENOTSUP) {
702                                 return NT_STATUS_EAS_NOT_SUPPORTED;
703                         }
704 #endif
705                         return map_nt_error_from_unix(errno);
706                 }
707
708         }
709         return NT_STATUS_OK;
710 }
711 /****************************************************************************
712  Read a list of EA names from an incoming data buffer. Create an ea_list with them.
713 ****************************************************************************/
714
715 static struct ea_list *read_ea_name_list(TALLOC_CTX *ctx, const char *pdata, size_t data_size)
716 {
717         struct ea_list *ea_list_head = NULL;
718         size_t converted_size, offset = 0;
719
720         while (offset + 2 < data_size) {
721                 struct ea_list *eal = talloc_zero(ctx, struct ea_list);
722                 unsigned int namelen = CVAL(pdata,offset);
723
724                 offset++; /* Go past the namelen byte. */
725
726                 /* integer wrap paranioa. */
727                 if ((offset + namelen < offset) || (offset + namelen < namelen) ||
728                                 (offset > data_size) || (namelen > data_size) ||
729                                 (offset + namelen >= data_size)) {
730                         break;
731                 }
732                 /* Ensure the name is null terminated. */
733                 if (pdata[offset + namelen] != '\0') {
734                         return NULL;
735                 }
736                 if (!pull_ascii_talloc(ctx, &eal->ea.name, &pdata[offset],
737                                        &converted_size)) {
738                         DEBUG(0,("read_ea_name_list: pull_ascii_talloc "
739                                  "failed: %s", strerror(errno)));
740                 }
741                 if (!eal->ea.name) {
742                         return NULL;
743                 }
744
745                 offset += (namelen + 1); /* Go past the name + terminating zero. */
746                 DLIST_ADD_END(ea_list_head, eal, struct ea_list *);
747                 DEBUG(10,("read_ea_name_list: read ea name %s\n", eal->ea.name));
748         }
749
750         return ea_list_head;
751 }
752
753 /****************************************************************************
754  Read a list of EA names and data from an incoming data buffer. Create an ea_list with them.
755 ****************************************************************************/
756
757 static struct ea_list *read_ea_list(TALLOC_CTX *ctx, const char *pdata, size_t data_size)
758 {
759         struct ea_list *ea_list_head = NULL;
760         size_t offset = 0;
761         size_t bytes_used = 0;
762
763         while (offset < data_size) {
764                 struct ea_list *eal = read_ea_list_entry(ctx, pdata + offset, data_size - offset, &bytes_used);
765
766                 if (!eal) {
767                         return NULL;
768                 }
769
770                 DLIST_ADD_END(ea_list_head, eal, struct ea_list *);
771                 offset += bytes_used;
772         }
773
774         return ea_list_head;
775 }
776
777 /****************************************************************************
778  Count the total EA size needed.
779 ****************************************************************************/
780
781 static size_t ea_list_size(struct ea_list *ealist)
782 {
783         fstring dos_ea_name;
784         struct ea_list *listp;
785         size_t ret = 0;
786
787         for (listp = ealist; listp; listp = listp->next) {
788                 push_ascii_fstring(dos_ea_name, listp->ea.name);
789                 ret += 4 + strlen(dos_ea_name) + 1 + listp->ea.value.length;
790         }
791         /* Add on 4 for total length. */
792         if (ret) {
793                 ret += 4;
794         }
795
796         return ret;
797 }
798
799 /****************************************************************************
800  Return a union of EA's from a file list and a list of names.
801  The TALLOC context for the two lists *MUST* be identical as we steal
802  memory from one list to add to another. JRA.
803 ****************************************************************************/
804
805 static struct ea_list *ea_list_union(struct ea_list *name_list, struct ea_list *file_list, size_t *total_ea_len)
806 {
807         struct ea_list *nlistp, *flistp;
808
809         for (nlistp = name_list; nlistp; nlistp = nlistp->next) {
810                 for (flistp = file_list; flistp; flistp = flistp->next) {
811                         if (strequal(nlistp->ea.name, flistp->ea.name)) {
812                                 break;
813                         }
814                 }
815
816                 if (flistp) {
817                         /* Copy the data from this entry. */
818                         nlistp->ea.flags = flistp->ea.flags;
819                         nlistp->ea.value = flistp->ea.value;
820                 } else {
821                         /* Null entry. */
822                         nlistp->ea.flags = 0;
823                         ZERO_STRUCT(nlistp->ea.value);
824                 }
825         }
826
827         *total_ea_len = ea_list_size(name_list);
828         return name_list;
829 }
830
831 /****************************************************************************
832   Send the required number of replies back.
833   We assume all fields other than the data fields are
834   set correctly for the type of call.
835   HACK ! Always assumes smb_setup field is zero.
836 ****************************************************************************/
837
838 void send_trans2_replies(connection_struct *conn,
839                         struct smb_request *req,
840                         NTSTATUS status,
841                          const char *params,
842                          int paramsize,
843                          const char *pdata,
844                          int datasize,
845                          int max_data_bytes)
846 {
847         /* As we are using a protocol > LANMAN1 then the max_send
848          variable must have been set in the sessetupX call.
849          This takes precedence over the max_xmit field in the
850          global struct. These different max_xmit variables should
851          be merged as this is now too confusing */
852
853         int data_to_send = datasize;
854         int params_to_send = paramsize;
855         int useable_space;
856         const char *pp = params;
857         const char *pd = pdata;
858         int params_sent_thistime, data_sent_thistime, total_sent_thistime;
859         int alignment_offset = 1; /* JRA. This used to be 3. Set to 1 to make netmon parse ok. */
860         int data_alignment_offset = 0;
861         bool overflow = False;
862         struct smbXsrv_connection *xconn = req->xconn;
863         struct smbd_server_connection *sconn = xconn->sconn;
864         int max_send = xconn->smb1.sessions.max_send;
865
866         /* Modify the data_to_send and datasize and set the error if
867            we're trying to send more than max_data_bytes. We still send
868            the part of the packet(s) that fit. Strange, but needed
869            for OS/2. */
870
871         if (max_data_bytes > 0 && datasize > max_data_bytes) {
872                 DEBUG(5,("send_trans2_replies: max_data_bytes %d exceeded by data %d\n",
873                         max_data_bytes, datasize ));
874                 datasize = data_to_send = max_data_bytes;
875                 overflow = True;
876         }
877
878         /* If there genuinely are no parameters or data to send just send the empty packet */
879
880         if(params_to_send == 0 && data_to_send == 0) {
881                 reply_outbuf(req, 10, 0);
882                 if (NT_STATUS_V(status)) {
883                         uint8_t eclass;
884                         uint32_t ecode;
885                         ntstatus_to_dos(status, &eclass, &ecode);
886                         error_packet_set((char *)req->outbuf,
887                                         eclass, ecode, status,
888                                         __LINE__,__FILE__);
889                 }
890                 show_msg((char *)req->outbuf);
891                 if (!srv_send_smb(sconn,
892                                 (char *)req->outbuf,
893                                 true, req->seqnum+1,
894                                 IS_CONN_ENCRYPTED(conn),
895                                 &req->pcd)) {
896                         exit_server_cleanly("send_trans2_replies: srv_send_smb failed.");
897                 }
898                 TALLOC_FREE(req->outbuf);
899                 return;
900         }
901
902         /* When sending params and data ensure that both are nicely aligned */
903         /* Only do this alignment when there is also data to send - else
904                 can cause NT redirector problems. */
905
906         if (((params_to_send % 4) != 0) && (data_to_send != 0))
907                 data_alignment_offset = 4 - (params_to_send % 4);
908
909         /* Space is bufsize minus Netbios over TCP header minus SMB header */
910         /* The alignment_offset is to align the param bytes on an even byte
911                 boundary. NT 4.0 Beta needs this to work correctly. */
912
913         useable_space = max_send - (smb_size
914                                     + 2 * 10 /* wct */
915                                     + alignment_offset
916                                     + data_alignment_offset);
917
918         if (useable_space < 0) {
919                 DEBUG(0, ("send_trans2_replies failed sanity useable_space "
920                           "= %d!!!", useable_space));
921                 exit_server_cleanly("send_trans2_replies: Not enough space");
922         }
923
924         while (params_to_send || data_to_send) {
925                 /* Calculate whether we will totally or partially fill this packet */
926
927                 total_sent_thistime = params_to_send + data_to_send;
928
929                 /* We can never send more than useable_space */
930                 /*
931                  * Note that 'useable_space' does not include the alignment offsets,
932                  * but we must include the alignment offsets in the calculation of
933                  * the length of the data we send over the wire, as the alignment offsets
934                  * are sent here. Fix from Marc_Jacobsen@hp.com.
935                  */
936
937                 total_sent_thistime = MIN(total_sent_thistime, useable_space);
938
939                 reply_outbuf(req, 10, total_sent_thistime + alignment_offset
940                              + data_alignment_offset);
941
942                 /* Set total params and data to be sent */
943                 SSVAL(req->outbuf,smb_tprcnt,paramsize);
944                 SSVAL(req->outbuf,smb_tdrcnt,datasize);
945
946                 /* Calculate how many parameters and data we can fit into
947                  * this packet. Parameters get precedence
948                  */
949
950                 params_sent_thistime = MIN(params_to_send,useable_space);
951                 data_sent_thistime = useable_space - params_sent_thistime;
952                 data_sent_thistime = MIN(data_sent_thistime,data_to_send);
953
954                 SSVAL(req->outbuf,smb_prcnt, params_sent_thistime);
955
956                 /* smb_proff is the offset from the start of the SMB header to the
957                         parameter bytes, however the first 4 bytes of outbuf are
958                         the Netbios over TCP header. Thus use smb_base() to subtract
959                         them from the calculation */
960
961                 SSVAL(req->outbuf,smb_proff,
962                       ((smb_buf(req->outbuf)+alignment_offset)
963                        - smb_base(req->outbuf)));
964
965                 if(params_sent_thistime == 0)
966                         SSVAL(req->outbuf,smb_prdisp,0);
967                 else
968                         /* Absolute displacement of param bytes sent in this packet */
969                         SSVAL(req->outbuf,smb_prdisp,pp - params);
970
971                 SSVAL(req->outbuf,smb_drcnt, data_sent_thistime);
972                 if(data_sent_thistime == 0) {
973                         SSVAL(req->outbuf,smb_droff,0);
974                         SSVAL(req->outbuf,smb_drdisp, 0);
975                 } else {
976                         /* The offset of the data bytes is the offset of the
977                                 parameter bytes plus the number of parameters being sent this time */
978                         SSVAL(req->outbuf, smb_droff,
979                               ((smb_buf(req->outbuf)+alignment_offset)
980                                - smb_base(req->outbuf))
981                               + params_sent_thistime + data_alignment_offset);
982                         SSVAL(req->outbuf,smb_drdisp, pd - pdata);
983                 }
984
985                 /* Initialize the padding for alignment */
986
987                 if (alignment_offset != 0) {
988                         memset(smb_buf(req->outbuf), 0, alignment_offset);
989                 }
990
991                 /* Copy the param bytes into the packet */
992
993                 if(params_sent_thistime) {
994                         memcpy((smb_buf(req->outbuf)+alignment_offset), pp,
995                                params_sent_thistime);
996                 }
997
998                 /* Copy in the data bytes */
999                 if(data_sent_thistime) {
1000                         if (data_alignment_offset != 0) {
1001                                 memset((smb_buf(req->outbuf)+alignment_offset+
1002                                         params_sent_thistime), 0,
1003                                        data_alignment_offset);
1004                         }
1005                         memcpy(smb_buf(req->outbuf)+alignment_offset
1006                                +params_sent_thistime+data_alignment_offset,
1007                                pd,data_sent_thistime);
1008                 }
1009
1010                 DEBUG(9,("t2_rep: params_sent_thistime = %d, data_sent_thistime = %d, useable_space = %d\n",
1011                         params_sent_thistime, data_sent_thistime, useable_space));
1012                 DEBUG(9,("t2_rep: params_to_send = %d, data_to_send = %d, paramsize = %d, datasize = %d\n",
1013                         params_to_send, data_to_send, paramsize, datasize));
1014
1015                 if (overflow) {
1016                         error_packet_set((char *)req->outbuf,
1017                                          ERRDOS,ERRbufferoverflow,
1018                                          STATUS_BUFFER_OVERFLOW,
1019                                          __LINE__,__FILE__);
1020                 } else if (NT_STATUS_V(status)) {
1021                         uint8_t eclass;
1022                         uint32_t ecode;
1023                         ntstatus_to_dos(status, &eclass, &ecode);
1024                         error_packet_set((char *)req->outbuf,
1025                                         eclass, ecode, status,
1026                                         __LINE__,__FILE__);
1027                 }
1028
1029                 /* Send the packet */
1030                 show_msg((char *)req->outbuf);
1031                 if (!srv_send_smb(sconn,
1032                                 (char *)req->outbuf,
1033                                 true, req->seqnum+1,
1034                                 IS_CONN_ENCRYPTED(conn),
1035                                 &req->pcd))
1036                         exit_server_cleanly("send_trans2_replies: srv_send_smb failed.");
1037
1038                 TALLOC_FREE(req->outbuf);
1039
1040                 pp += params_sent_thistime;
1041                 pd += data_sent_thistime;
1042
1043                 params_to_send -= params_sent_thistime;
1044                 data_to_send -= data_sent_thistime;
1045
1046                 /* Sanity check */
1047                 if(params_to_send < 0 || data_to_send < 0) {
1048                         DEBUG(0,("send_trans2_replies failed sanity check pts = %d, dts = %d\n!!!",
1049                                 params_to_send, data_to_send));
1050                         return;
1051                 }
1052         }
1053
1054         return;
1055 }
1056
1057 /****************************************************************************
1058  Reply to a TRANSACT2_OPEN.
1059 ****************************************************************************/
1060
1061 static void call_trans2open(connection_struct *conn,
1062                             struct smb_request *req,
1063                             char **pparams, int total_params,
1064                             char **ppdata, int total_data,
1065                             unsigned int max_data_bytes)
1066 {
1067         struct smb_filename *smb_fname = NULL;
1068         char *params = *pparams;
1069         char *pdata = *ppdata;
1070         int deny_mode;
1071         int32 open_attr;
1072         bool oplock_request;
1073 #if 0
1074         bool return_additional_info;
1075         int16 open_sattr;
1076         time_t open_time;
1077 #endif
1078         int open_ofun;
1079         uint32 open_size;
1080         char *pname;
1081         char *fname = NULL;
1082         off_t size=0;
1083         int fattr=0,mtime=0;
1084         SMB_INO_T inode = 0;
1085         int smb_action = 0;
1086         files_struct *fsp;
1087         struct ea_list *ea_list = NULL;
1088         uint16 flags = 0;
1089         NTSTATUS status;
1090         uint32 access_mask;
1091         uint32 share_mode;
1092         uint32 create_disposition;
1093         uint32 create_options = 0;
1094         uint32_t private_flags = 0;
1095         TALLOC_CTX *ctx = talloc_tos();
1096
1097         /*
1098          * Ensure we have enough parameters to perform the operation.
1099          */
1100
1101         if (total_params < 29) {
1102                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1103                 goto out;
1104         }
1105
1106         flags = SVAL(params, 0);
1107         deny_mode = SVAL(params, 2);
1108         open_attr = SVAL(params,6);
1109         oplock_request = (flags & REQUEST_OPLOCK) ? EXCLUSIVE_OPLOCK : 0;
1110         if (oplock_request) {
1111                 oplock_request |= (flags & REQUEST_BATCH_OPLOCK) ? BATCH_OPLOCK : 0;
1112         }
1113
1114 #if 0
1115         return_additional_info = BITSETW(params,0);
1116         open_sattr = SVAL(params, 4);
1117         open_time = make_unix_date3(params+8);
1118 #endif
1119         open_ofun = SVAL(params,12);
1120         open_size = IVAL(params,14);
1121         pname = &params[28];
1122
1123         if (IS_IPC(conn)) {
1124                 reply_nterror(req, NT_STATUS_NETWORK_ACCESS_DENIED);
1125                 goto out;
1126         }
1127
1128         srvstr_get_path(ctx, params, req->flags2, &fname, pname,
1129                         total_params - 28, STR_TERMINATE,
1130                         &status);
1131         if (!NT_STATUS_IS_OK(status)) {
1132                 reply_nterror(req, status);
1133                 goto out;
1134         }
1135
1136         DEBUG(3,("call_trans2open %s deny_mode=0x%x attr=%d ofun=0x%x size=%d\n",
1137                 fname, (unsigned int)deny_mode, (unsigned int)open_attr,
1138                 (unsigned int)open_ofun, open_size));
1139
1140         status = filename_convert(ctx,
1141                                 conn,
1142                                 req->flags2 & FLAGS2_DFS_PATHNAMES,
1143                                 fname,
1144                                 0,
1145                                 NULL,
1146                                 &smb_fname);
1147         if (!NT_STATUS_IS_OK(status)) {
1148                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
1149                         reply_botherror(req,
1150                                 NT_STATUS_PATH_NOT_COVERED,
1151                                 ERRSRV, ERRbadpath);
1152                         goto out;
1153                 }
1154                 reply_nterror(req, status);
1155                 goto out;
1156         }
1157
1158         if (open_ofun == 0) {
1159                 reply_nterror(req, NT_STATUS_OBJECT_NAME_COLLISION);
1160                 goto out;
1161         }
1162
1163         if (!map_open_params_to_ntcreate(smb_fname->base_name, deny_mode,
1164                                          open_ofun,
1165                                          &access_mask, &share_mode,
1166                                          &create_disposition,
1167                                          &create_options,
1168                                          &private_flags)) {
1169                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
1170                 goto out;
1171         }
1172
1173         /* Any data in this call is an EA list. */
1174         if (total_data && (total_data != 4)) {
1175                 if (total_data < 10) {
1176                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1177                         goto out;
1178                 }
1179
1180                 if (IVAL(pdata,0) > total_data) {
1181                         DEBUG(10,("call_trans2open: bad total data size (%u) > %u\n",
1182                                 IVAL(pdata,0), (unsigned int)total_data));
1183                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1184                         goto out;
1185                 }
1186
1187                 ea_list = read_ea_list(talloc_tos(), pdata + 4,
1188                                        total_data - 4);
1189                 if (!ea_list) {
1190                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1191                         goto out;
1192                 }
1193
1194                 if (!lp_ea_support(SNUM(conn))) {
1195                         reply_nterror(req, NT_STATUS_EAS_NOT_SUPPORTED);
1196                         goto out;
1197                 }
1198
1199                 if (ea_list_has_invalid_name(ea_list)) {
1200                         int param_len = 30;
1201                         *pparams = (char *)SMB_REALLOC(*pparams, param_len);
1202                         if(*pparams == NULL ) {
1203                                 reply_nterror(req, NT_STATUS_NO_MEMORY);
1204                                 goto out;
1205                         }
1206                         params = *pparams;
1207                         memset(params, '\0', param_len);
1208                         send_trans2_replies(conn, req, STATUS_INVALID_EA_NAME,
1209                                 params, param_len, NULL, 0, max_data_bytes);
1210                         goto out;
1211                 }
1212         }
1213
1214         status = SMB_VFS_CREATE_FILE(
1215                 conn,                                   /* conn */
1216                 req,                                    /* req */
1217                 0,                                      /* root_dir_fid */
1218                 smb_fname,                              /* fname */
1219                 access_mask,                            /* access_mask */
1220                 share_mode,                             /* share_access */
1221                 create_disposition,                     /* create_disposition*/
1222                 create_options,                         /* create_options */
1223                 open_attr,                              /* file_attributes */
1224                 oplock_request,                         /* oplock_request */
1225                 NULL,                                   /* lease */
1226                 open_size,                              /* allocation_size */
1227                 private_flags,
1228                 NULL,                                   /* sd */
1229                 ea_list,                                /* ea_list */
1230                 &fsp,                                   /* result */
1231                 &smb_action);                           /* psbuf */
1232
1233         if (!NT_STATUS_IS_OK(status)) {
1234                 if (open_was_deferred(req->sconn, req->mid)) {
1235                         /* We have re-scheduled this call. */
1236                         goto out;
1237                 }
1238                 reply_openerror(req, status);
1239                 goto out;
1240         }
1241
1242         size = get_file_size_stat(&smb_fname->st);
1243         fattr = dos_mode(conn, smb_fname);
1244         mtime = convert_timespec_to_time_t(smb_fname->st.st_ex_mtime);
1245         inode = smb_fname->st.st_ex_ino;
1246         if (fattr & FILE_ATTRIBUTE_DIRECTORY) {
1247                 close_file(req, fsp, ERROR_CLOSE);
1248                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
1249                 goto out;
1250         }
1251
1252         /* Realloc the size of parameters and data we will return */
1253         *pparams = (char *)SMB_REALLOC(*pparams, 30);
1254         if(*pparams == NULL ) {
1255                 reply_nterror(req, NT_STATUS_NO_MEMORY);
1256                 goto out;
1257         }
1258         params = *pparams;
1259
1260         SSVAL(params,0,fsp->fnum);
1261         SSVAL(params,2,fattr);
1262         srv_put_dos_date2(params,4, mtime);
1263         SIVAL(params,8, (uint32)size);
1264         SSVAL(params,12,deny_mode);
1265         SSVAL(params,14,0); /* open_type - file or directory. */
1266         SSVAL(params,16,0); /* open_state - only valid for IPC device. */
1267
1268         if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
1269                 smb_action |= EXTENDED_OPLOCK_GRANTED;
1270         }
1271
1272         SSVAL(params,18,smb_action);
1273
1274         /*
1275          * WARNING - this may need to be changed if SMB_INO_T <> 4 bytes.
1276          */
1277         SIVAL(params,20,inode);
1278         SSVAL(params,24,0); /* Padding. */
1279         if (flags & 8) {
1280                 uint32 ea_size = estimate_ea_size(conn, fsp,
1281                                                   smb_fname);
1282                 SIVAL(params, 26, ea_size);
1283         } else {
1284                 SIVAL(params, 26, 0);
1285         }
1286
1287         /* Send the required number of replies */
1288         send_trans2_replies(conn, req, NT_STATUS_OK, params, 30, *ppdata, 0, max_data_bytes);
1289  out:
1290         TALLOC_FREE(smb_fname);
1291 }
1292
1293 /*********************************************************
1294  Routine to check if a given string matches exactly.
1295  as a special case a mask of "." does NOT match. That
1296  is required for correct wildcard semantics
1297  Case can be significant or not.
1298 **********************************************************/
1299
1300 static bool exact_match(bool has_wild,
1301                         bool case_sensitive,
1302                         const char *str,
1303                         const char *mask)
1304 {
1305         if (mask[0] == '.' && mask[1] == 0) {
1306                 return false;
1307         }
1308
1309         if (has_wild) {
1310                 return false;
1311         }
1312
1313         if (case_sensitive) {
1314                 return strcmp(str,mask)==0;
1315         } else {
1316                 return strcasecmp_m(str,mask) == 0;
1317         }
1318 }
1319
1320 /****************************************************************************
1321  Return the filetype for UNIX extensions.
1322 ****************************************************************************/
1323
1324 static uint32 unix_filetype(mode_t mode)
1325 {
1326         if(S_ISREG(mode))
1327                 return UNIX_TYPE_FILE;
1328         else if(S_ISDIR(mode))
1329                 return UNIX_TYPE_DIR;
1330 #ifdef S_ISLNK
1331         else if(S_ISLNK(mode))
1332                 return UNIX_TYPE_SYMLINK;
1333 #endif
1334 #ifdef S_ISCHR
1335         else if(S_ISCHR(mode))
1336                 return UNIX_TYPE_CHARDEV;
1337 #endif
1338 #ifdef S_ISBLK
1339         else if(S_ISBLK(mode))
1340                 return UNIX_TYPE_BLKDEV;
1341 #endif
1342 #ifdef S_ISFIFO
1343         else if(S_ISFIFO(mode))
1344                 return UNIX_TYPE_FIFO;
1345 #endif
1346 #ifdef S_ISSOCK
1347         else if(S_ISSOCK(mode))
1348                 return UNIX_TYPE_SOCKET;
1349 #endif
1350
1351         DEBUG(0,("unix_filetype: unknown filetype %u\n", (unsigned)mode));
1352         return UNIX_TYPE_UNKNOWN;
1353 }
1354
1355 /****************************************************************************
1356  Map wire perms onto standard UNIX permissions. Obey share restrictions.
1357 ****************************************************************************/
1358
1359 enum perm_type { PERM_NEW_FILE, PERM_NEW_DIR, PERM_EXISTING_FILE, PERM_EXISTING_DIR};
1360
1361 static NTSTATUS unix_perms_from_wire( connection_struct *conn,
1362                                 const SMB_STRUCT_STAT *psbuf,
1363                                 uint32 perms,
1364                                 enum perm_type ptype,
1365                                 mode_t *ret_perms)
1366 {
1367         mode_t ret = 0;
1368
1369         if (perms == SMB_MODE_NO_CHANGE) {
1370                 if (!VALID_STAT(*psbuf)) {
1371                         return NT_STATUS_INVALID_PARAMETER;
1372                 } else {
1373                         *ret_perms = psbuf->st_ex_mode;
1374                         return NT_STATUS_OK;
1375                 }
1376         }
1377
1378         ret |= ((perms & UNIX_X_OTH ) ? S_IXOTH : 0);
1379         ret |= ((perms & UNIX_W_OTH ) ? S_IWOTH : 0);
1380         ret |= ((perms & UNIX_R_OTH ) ? S_IROTH : 0);
1381         ret |= ((perms & UNIX_X_GRP ) ? S_IXGRP : 0);
1382         ret |= ((perms & UNIX_W_GRP ) ? S_IWGRP : 0);
1383         ret |= ((perms & UNIX_R_GRP ) ? S_IRGRP : 0);
1384         ret |= ((perms & UNIX_X_USR ) ? S_IXUSR : 0);
1385         ret |= ((perms & UNIX_W_USR ) ? S_IWUSR : 0);
1386         ret |= ((perms & UNIX_R_USR ) ? S_IRUSR : 0);
1387 #ifdef S_ISVTX
1388         ret |= ((perms & UNIX_STICKY ) ? S_ISVTX : 0);
1389 #endif
1390 #ifdef S_ISGID
1391         ret |= ((perms & UNIX_SET_GID ) ? S_ISGID : 0);
1392 #endif
1393 #ifdef S_ISUID
1394         ret |= ((perms & UNIX_SET_UID ) ? S_ISUID : 0);
1395 #endif
1396
1397         if (ptype == PERM_NEW_FILE) {
1398                 /*
1399                  * "create mask"/"force create mode" are
1400                  * only applied to new files, not existing ones.
1401                  */
1402                 ret &= lp_create_mask(SNUM(conn));
1403                 /* Add in force bits */
1404                 ret |= lp_force_create_mode(SNUM(conn));
1405         } else if (ptype == PERM_NEW_DIR) {
1406                 /*
1407                  * "directory mask"/"force directory mode" are
1408                  * only applied to new directories, not existing ones.
1409                  */
1410                 ret &= lp_directory_mask(SNUM(conn));
1411                 /* Add in force bits */
1412                 ret |= lp_force_directory_mode(SNUM(conn));
1413         }
1414
1415         *ret_perms = ret;
1416         return NT_STATUS_OK;
1417 }
1418
1419 /****************************************************************************
1420  Needed to show the msdfs symlinks as directories. Modifies psbuf
1421  to be a directory if it's a msdfs link.
1422 ****************************************************************************/
1423
1424 static bool check_msdfs_link(connection_struct *conn,
1425                                 const char *pathname,
1426                                 SMB_STRUCT_STAT *psbuf)
1427 {
1428         int saved_errno = errno;
1429         if(lp_host_msdfs() &&
1430                 lp_msdfs_root(SNUM(conn)) &&
1431                 is_msdfs_link(conn, pathname, psbuf)) {
1432
1433                 DEBUG(5,("check_msdfs_link: Masquerading msdfs link %s "
1434                         "as a directory\n",
1435                         pathname));
1436                 psbuf->st_ex_mode = (psbuf->st_ex_mode & 0xFFF) | S_IFDIR;
1437                 errno = saved_errno;
1438                 return true;
1439         }
1440         errno = saved_errno;
1441         return false;
1442 }
1443
1444
1445 /****************************************************************************
1446  Get a level dependent lanman2 dir entry.
1447 ****************************************************************************/
1448
1449 struct smbd_dirptr_lanman2_state {
1450         connection_struct *conn;
1451         uint32_t info_level;
1452         bool check_mangled_names;
1453         bool has_wild;
1454         bool got_exact_match;
1455 };
1456
1457 static bool smbd_dirptr_lanman2_match_fn(TALLOC_CTX *ctx,
1458                                          void *private_data,
1459                                          const char *dname,
1460                                          const char *mask,
1461                                          char **_fname)
1462 {
1463         struct smbd_dirptr_lanman2_state *state =
1464                 (struct smbd_dirptr_lanman2_state *)private_data;
1465         bool ok;
1466         char mangled_name[13]; /* mangled 8.3 name. */
1467         bool got_match;
1468         const char *fname;
1469
1470         /* Mangle fname if it's an illegal name. */
1471         if (mangle_must_mangle(dname, state->conn->params)) {
1472                 ok = name_to_8_3(dname, mangled_name,
1473                                  true, state->conn->params);
1474                 if (!ok) {
1475                         return false;
1476                 }
1477                 fname = mangled_name;
1478         } else {
1479                 fname = dname;
1480         }
1481
1482         got_match = exact_match(state->has_wild,
1483                                 state->conn->case_sensitive,
1484                                 fname, mask);
1485         state->got_exact_match = got_match;
1486         if (!got_match) {
1487                 got_match = mask_match(fname, mask,
1488                                        state->conn->case_sensitive);
1489         }
1490
1491         if(!got_match && state->check_mangled_names &&
1492            !mangle_is_8_3(fname, false, state->conn->params)) {
1493                 /*
1494                  * It turns out that NT matches wildcards against
1495                  * both long *and* short names. This may explain some
1496                  * of the wildcard wierdness from old DOS clients
1497                  * that some people have been seeing.... JRA.
1498                  */
1499                 /* Force the mangling into 8.3. */
1500                 ok = name_to_8_3(fname, mangled_name,
1501                                  false, state->conn->params);
1502                 if (!ok) {
1503                         return false;
1504                 }
1505
1506                 got_match = exact_match(state->has_wild,
1507                                         state->conn->case_sensitive,
1508                                         mangled_name, mask);
1509                 state->got_exact_match = got_match;
1510                 if (!got_match) {
1511                         got_match = mask_match(mangled_name, mask,
1512                                                state->conn->case_sensitive);
1513                 }
1514         }
1515
1516         if (!got_match) {
1517                 return false;
1518         }
1519
1520         *_fname = talloc_strdup(ctx, fname);
1521         if (*_fname == NULL) {
1522                 return false;
1523         }
1524
1525         return true;
1526 }
1527
1528 static bool smbd_dirptr_lanman2_mode_fn(TALLOC_CTX *ctx,
1529                                         void *private_data,
1530                                         struct smb_filename *smb_fname,
1531                                         uint32_t *_mode)
1532 {
1533         struct smbd_dirptr_lanman2_state *state =
1534                 (struct smbd_dirptr_lanman2_state *)private_data;
1535         bool ms_dfs_link = false;
1536         uint32_t mode = 0;
1537
1538         if (INFO_LEVEL_IS_UNIX(state->info_level)) {
1539                 if (SMB_VFS_LSTAT(state->conn, smb_fname) != 0) {
1540                         DEBUG(5,("smbd_dirptr_lanman2_mode_fn: "
1541                                  "Couldn't lstat [%s] (%s)\n",
1542                                  smb_fname_str_dbg(smb_fname),
1543                                  strerror(errno)));
1544                         return false;
1545                 }
1546         } else if (!VALID_STAT(smb_fname->st) &&
1547                    SMB_VFS_STAT(state->conn, smb_fname) != 0) {
1548                 /* Needed to show the msdfs symlinks as
1549                  * directories */
1550
1551                 ms_dfs_link = check_msdfs_link(state->conn,
1552                                                smb_fname->base_name,
1553                                                &smb_fname->st);
1554                 if (!ms_dfs_link) {
1555                         DEBUG(5,("smbd_dirptr_lanman2_mode_fn: "
1556                                  "Couldn't stat [%s] (%s)\n",
1557                                  smb_fname_str_dbg(smb_fname),
1558                                  strerror(errno)));
1559                         return false;
1560                 }
1561         }
1562
1563         if (ms_dfs_link) {
1564                 mode = dos_mode_msdfs(state->conn, smb_fname);
1565         } else {
1566                 mode = dos_mode(state->conn, smb_fname);
1567         }
1568
1569         *_mode = mode;
1570         return true;
1571 }
1572
1573 static bool smbd_marshall_dir_entry(TALLOC_CTX *ctx,
1574                                     connection_struct *conn,
1575                                     uint16_t flags2,
1576                                     uint32_t info_level,
1577                                     struct ea_list *name_list,
1578                                     bool check_mangled_names,
1579                                     bool requires_resume_key,
1580                                     uint32_t mode,
1581                                     const char *fname,
1582                                     const struct smb_filename *smb_fname,
1583                                     int space_remaining,
1584                                     uint8_t align,
1585                                     bool do_pad,
1586                                     char *base_data,
1587                                     char **ppdata,
1588                                     char *end_data,
1589                                     bool *out_of_space,
1590                                     uint64_t *last_entry_off)
1591 {
1592         char *p, *q, *pdata = *ppdata;
1593         uint32_t reskey=0;
1594         uint64_t file_size = 0;
1595         uint64_t allocation_size = 0;
1596         uint64_t file_index = 0;
1597         uint32_t len;
1598         struct timespec mdate_ts, adate_ts, cdate_ts, create_date_ts;
1599         time_t mdate = (time_t)0, adate = (time_t)0, create_date = (time_t)0;
1600         char *nameptr;
1601         char *last_entry_ptr;
1602         bool was_8_3;
1603         int off;
1604         int pad = 0;
1605
1606         *out_of_space = false;
1607
1608         ZERO_STRUCT(mdate_ts);
1609         ZERO_STRUCT(adate_ts);
1610         ZERO_STRUCT(create_date_ts);
1611         ZERO_STRUCT(cdate_ts);
1612
1613         if (!(mode & FILE_ATTRIBUTE_DIRECTORY)) {
1614                 file_size = get_file_size_stat(&smb_fname->st);
1615         }
1616         allocation_size = SMB_VFS_GET_ALLOC_SIZE(conn, NULL, &smb_fname->st);
1617
1618         file_index = get_FileIndex(conn, &smb_fname->st);
1619
1620         mdate_ts = smb_fname->st.st_ex_mtime;
1621         adate_ts = smb_fname->st.st_ex_atime;
1622         create_date_ts = get_create_timespec(conn, NULL, smb_fname);
1623         cdate_ts = get_change_timespec(conn, NULL, smb_fname);
1624
1625         if (lp_dos_filetime_resolution(SNUM(conn))) {
1626                 dos_filetime_timespec(&create_date_ts);
1627                 dos_filetime_timespec(&mdate_ts);
1628                 dos_filetime_timespec(&adate_ts);
1629                 dos_filetime_timespec(&cdate_ts);
1630         }
1631
1632         create_date = convert_timespec_to_time_t(create_date_ts);
1633         mdate = convert_timespec_to_time_t(mdate_ts);
1634         adate = convert_timespec_to_time_t(adate_ts);
1635
1636         /* align the record */
1637         SMB_ASSERT(align >= 1);
1638
1639         off = (int)PTR_DIFF(pdata, base_data);
1640         pad = (off + (align-1)) & ~(align-1);
1641         pad -= off;
1642
1643         if (pad && pad > space_remaining) {
1644                 *out_of_space = true;
1645                 DEBUG(9,("smbd_marshall_dir_entry: out of space "
1646                         "for padding (wanted %u, had %d)\n",
1647                         (unsigned int)pad,
1648                         space_remaining ));
1649                 return false; /* Not finished - just out of space */
1650         }
1651
1652         off += pad;
1653         /* initialize padding to 0 */
1654         if (pad) {
1655                 memset(pdata, 0, pad);
1656         }
1657         space_remaining -= pad;
1658
1659         DEBUG(10,("smbd_marshall_dir_entry: space_remaining = %d\n",
1660                 space_remaining ));
1661
1662         pdata += pad;
1663         p = pdata;
1664         last_entry_ptr = p;
1665
1666         pad = 0;
1667         off = 0;
1668
1669         switch (info_level) {
1670         case SMB_FIND_INFO_STANDARD:
1671                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_INFO_STANDARD\n"));
1672                 if(requires_resume_key) {
1673                         SIVAL(p,0,reskey);
1674                         p += 4;
1675                 }
1676                 srv_put_dos_date2(p,0,create_date);
1677                 srv_put_dos_date2(p,4,adate);
1678                 srv_put_dos_date2(p,8,mdate);
1679                 SIVAL(p,12,(uint32)file_size);
1680                 SIVAL(p,16,(uint32)allocation_size);
1681                 SSVAL(p,20,mode);
1682                 p += 23;
1683                 nameptr = p;
1684                 if (flags2 & FLAGS2_UNICODE_STRINGS) {
1685                         p += ucs2_align(base_data, p, 0);
1686                 }
1687                 len = srvstr_push(base_data, flags2, p,
1688                                   fname, PTR_DIFF(end_data, p),
1689                                   STR_TERMINATE);
1690                 if (flags2 & FLAGS2_UNICODE_STRINGS) {
1691                         if (len > 2) {
1692                                 SCVAL(nameptr, -1, len - 2);
1693                         } else {
1694                                 SCVAL(nameptr, -1, 0);
1695                         }
1696                 } else {
1697                         if (len > 1) {
1698                                 SCVAL(nameptr, -1, len - 1);
1699                         } else {
1700                                 SCVAL(nameptr, -1, 0);
1701                         }
1702                 }
1703                 p += len;
1704                 break;
1705
1706         case SMB_FIND_EA_SIZE:
1707                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_EA_SIZE\n"));
1708                 if (requires_resume_key) {
1709                         SIVAL(p,0,reskey);
1710                         p += 4;
1711                 }
1712                 srv_put_dos_date2(p,0,create_date);
1713                 srv_put_dos_date2(p,4,adate);
1714                 srv_put_dos_date2(p,8,mdate);
1715                 SIVAL(p,12,(uint32)file_size);
1716                 SIVAL(p,16,(uint32)allocation_size);
1717                 SSVAL(p,20,mode);
1718                 {
1719                         unsigned int ea_size = estimate_ea_size(conn, NULL,
1720                                                                 smb_fname);
1721                         SIVAL(p,22,ea_size); /* Extended attributes */
1722                 }
1723                 p += 27;
1724                 nameptr = p - 1;
1725                 len = srvstr_push(base_data, flags2,
1726                                   p, fname, PTR_DIFF(end_data, p),
1727                                   STR_TERMINATE | STR_NOALIGN);
1728                 if (flags2 & FLAGS2_UNICODE_STRINGS) {
1729                         if (len > 2) {
1730                                 len -= 2;
1731                         } else {
1732                                 len = 0;
1733                         }
1734                 } else {
1735                         if (len > 1) {
1736                                 len -= 1;
1737                         } else {
1738                                 len = 0;
1739                         }
1740                 }
1741                 SCVAL(nameptr,0,len);
1742                 p += len;
1743                 SCVAL(p,0,0); p += 1; /* Extra zero byte ? - why.. */
1744                 break;
1745
1746         case SMB_FIND_EA_LIST:
1747         {
1748                 struct ea_list *file_list = NULL;
1749                 size_t ea_len = 0;
1750                 NTSTATUS status;
1751
1752                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_EA_LIST\n"));
1753                 if (!name_list) {
1754                         return false;
1755                 }
1756                 if (requires_resume_key) {
1757                         SIVAL(p,0,reskey);
1758                         p += 4;
1759                 }
1760                 srv_put_dos_date2(p,0,create_date);
1761                 srv_put_dos_date2(p,4,adate);
1762                 srv_put_dos_date2(p,8,mdate);
1763                 SIVAL(p,12,(uint32)file_size);
1764                 SIVAL(p,16,(uint32)allocation_size);
1765                 SSVAL(p,20,mode);
1766                 p += 22; /* p now points to the EA area. */
1767
1768                 status = get_ea_list_from_file(ctx, conn, NULL,
1769                                                smb_fname,
1770                                                &ea_len, &file_list);
1771                 if (!NT_STATUS_IS_OK(status)) {
1772                         file_list = NULL;
1773                 }
1774                 name_list = ea_list_union(name_list, file_list, &ea_len);
1775
1776                 /* We need to determine if this entry will fit in the space available. */
1777                 /* Max string size is 255 bytes. */
1778                 if (PTR_DIFF(p + 255 + ea_len,pdata) > space_remaining) {
1779                         *out_of_space = true;
1780                         DEBUG(9,("smbd_marshall_dir_entry: out of space "
1781                                 "(wanted %u, had %d)\n",
1782                                 (unsigned int)PTR_DIFF(p + 255 + ea_len,pdata),
1783                                 space_remaining ));
1784                         return False; /* Not finished - just out of space */
1785                 }
1786
1787                 /* Push the ea_data followed by the name. */
1788                 p += fill_ea_buffer(ctx, p, space_remaining, conn, name_list);
1789                 nameptr = p;
1790                 len = srvstr_push(base_data, flags2,
1791                                   p + 1, fname, PTR_DIFF(end_data, p+1),
1792                                   STR_TERMINATE | STR_NOALIGN);
1793                 if (flags2 & FLAGS2_UNICODE_STRINGS) {
1794                         if (len > 2) {
1795                                 len -= 2;
1796                         } else {
1797                                 len = 0;
1798                         }
1799                 } else {
1800                         if (len > 1) {
1801                                 len -= 1;
1802                         } else {
1803                                 len = 0;
1804                         }
1805                 }
1806                 SCVAL(nameptr,0,len);
1807                 p += len + 1;
1808                 SCVAL(p,0,0); p += 1; /* Extra zero byte ? - why.. */
1809                 break;
1810         }
1811
1812         case SMB_FIND_FILE_BOTH_DIRECTORY_INFO:
1813                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_BOTH_DIRECTORY_INFO\n"));
1814                 was_8_3 = mangle_is_8_3(fname, True, conn->params);
1815                 p += 4;
1816                 SIVAL(p,0,reskey); p += 4;
1817                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
1818                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
1819                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
1820                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
1821                 SOFF_T(p,0,file_size); p += 8;
1822                 SOFF_T(p,0,allocation_size); p += 8;
1823                 SIVAL(p,0,mode); p += 4;
1824                 q = p; p += 4; /* q is placeholder for name length. */
1825                 if (mode & FILE_ATTRIBUTE_REPARSE_POINT) {
1826                         SIVAL(p, 0, IO_REPARSE_TAG_DFS);
1827                 } else {
1828                         unsigned int ea_size = estimate_ea_size(conn, NULL,
1829                                                                 smb_fname);
1830                         SIVAL(p,0,ea_size); /* Extended attributes */
1831                 }
1832                 p += 4;
1833                 /* Clear the short name buffer. This is
1834                  * IMPORTANT as not doing so will trigger
1835                  * a Win2k client bug. JRA.
1836                  */
1837                 if (!was_8_3 && check_mangled_names) {
1838                         char mangled_name[13]; /* mangled 8.3 name. */
1839                         if (!name_to_8_3(fname,mangled_name,True,
1840                                            conn->params)) {
1841                                 /* Error - mangle failed ! */
1842                                 memset(mangled_name,'\0',12);
1843                         }
1844                         mangled_name[12] = 0;
1845                         len = srvstr_push(base_data, flags2,
1846                                           p+2, mangled_name, 24,
1847                                           STR_UPPER|STR_UNICODE);
1848                         if (len < 24) {
1849                                 memset(p + 2 + len,'\0',24 - len);
1850                         }
1851                         SSVAL(p, 0, len);
1852                 } else {
1853                         memset(p,'\0',26);
1854                 }
1855                 p += 2 + 24;
1856                 len = srvstr_push(base_data, flags2, p,
1857                                   fname, PTR_DIFF(end_data, p),
1858                                   STR_TERMINATE_ASCII);
1859                 SIVAL(q,0,len);
1860                 p += len;
1861
1862                 len = PTR_DIFF(p, pdata);
1863                 pad = (len + (align-1)) & ~(align-1);
1864                 /*
1865                  * offset to the next entry, the caller
1866                  * will overwrite it for the last entry
1867                  * that's why we always include the padding
1868                  */
1869                 SIVAL(pdata,0,pad);
1870                 /*
1871                  * set padding to zero
1872                  */
1873                 if (do_pad) {
1874                         memset(p, 0, pad - len);
1875                         p = pdata + pad;
1876                 } else {
1877                         p = pdata + len;
1878                 }
1879                 break;
1880
1881         case SMB_FIND_FILE_DIRECTORY_INFO:
1882                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_DIRECTORY_INFO\n"));
1883                 p += 4;
1884                 SIVAL(p,0,reskey); p += 4;
1885                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
1886                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
1887                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
1888                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
1889                 SOFF_T(p,0,file_size); p += 8;
1890                 SOFF_T(p,0,allocation_size); p += 8;
1891                 SIVAL(p,0,mode); p += 4;
1892                 len = srvstr_push(base_data, flags2,
1893                                   p + 4, fname, PTR_DIFF(end_data, p+4),
1894                                   STR_TERMINATE_ASCII);
1895                 SIVAL(p,0,len);
1896                 p += 4 + len;
1897
1898                 len = PTR_DIFF(p, pdata);
1899                 pad = (len + (align-1)) & ~(align-1);
1900                 /*
1901                  * offset to the next entry, the caller
1902                  * will overwrite it for the last entry
1903                  * that's why we always include the padding
1904                  */
1905                 SIVAL(pdata,0,pad);
1906                 /*
1907                  * set padding to zero
1908                  */
1909                 if (do_pad) {
1910                         memset(p, 0, pad - len);
1911                         p = pdata + pad;
1912                 } else {
1913                         p = pdata + len;
1914                 }
1915                 break;
1916
1917         case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
1918                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_FULL_DIRECTORY_INFO\n"));
1919                 p += 4;
1920                 SIVAL(p,0,reskey); p += 4;
1921                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
1922                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
1923                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
1924                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
1925                 SOFF_T(p,0,file_size); p += 8;
1926                 SOFF_T(p,0,allocation_size); p += 8;
1927                 SIVAL(p,0,mode); p += 4;
1928                 q = p; p += 4; /* q is placeholder for name length. */
1929                 {
1930                         unsigned int ea_size = estimate_ea_size(conn, NULL,
1931                                                                 smb_fname);
1932                         SIVAL(p,0,ea_size); /* Extended attributes */
1933                         p +=4;
1934                 }
1935                 len = srvstr_push(base_data, flags2, p,
1936                                   fname, PTR_DIFF(end_data, p),
1937                                   STR_TERMINATE_ASCII);
1938                 SIVAL(q, 0, len);
1939                 p += len;
1940
1941                 len = PTR_DIFF(p, pdata);
1942                 pad = (len + (align-1)) & ~(align-1);
1943                 /*
1944                  * offset to the next entry, the caller
1945                  * will overwrite it for the last entry
1946                  * that's why we always include the padding
1947                  */
1948                 SIVAL(pdata,0,pad);
1949                 /*
1950                  * set padding to zero
1951                  */
1952                 if (do_pad) {
1953                         memset(p, 0, pad - len);
1954                         p = pdata + pad;
1955                 } else {
1956                         p = pdata + len;
1957                 }
1958                 break;
1959
1960         case SMB_FIND_FILE_NAMES_INFO:
1961                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_NAMES_INFO\n"));
1962                 p += 4;
1963                 SIVAL(p,0,reskey); p += 4;
1964                 p += 4;
1965                 /* this must *not* be null terminated or w2k gets in a loop trying to set an
1966                    acl on a dir (tridge) */
1967                 len = srvstr_push(base_data, flags2, p,
1968                                   fname, PTR_DIFF(end_data, p),
1969                                   STR_TERMINATE_ASCII);
1970                 SIVAL(p, -4, len);
1971                 p += len;
1972
1973                 len = PTR_DIFF(p, pdata);
1974                 pad = (len + (align-1)) & ~(align-1);
1975                 /*
1976                  * offset to the next entry, the caller
1977                  * will overwrite it for the last entry
1978                  * that's why we always include the padding
1979                  */
1980                 SIVAL(pdata,0,pad);
1981                 /*
1982                  * set padding to zero
1983                  */
1984                 if (do_pad) {
1985                         memset(p, 0, pad - len);
1986                         p = pdata + pad;
1987                 } else {
1988                         p = pdata + len;
1989                 }
1990                 break;
1991
1992         case SMB_FIND_ID_FULL_DIRECTORY_INFO:
1993                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_ID_FULL_DIRECTORY_INFO\n"));
1994                 p += 4;
1995                 SIVAL(p,0,reskey); p += 4;
1996                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
1997                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
1998                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
1999                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
2000                 SOFF_T(p,0,file_size); p += 8;
2001                 SOFF_T(p,0,allocation_size); p += 8;
2002                 SIVAL(p,0,mode); p += 4;
2003                 q = p; p += 4; /* q is placeholder for name length. */
2004                 if (mode & FILE_ATTRIBUTE_REPARSE_POINT) {
2005                         SIVAL(p, 0, IO_REPARSE_TAG_DFS);
2006                 } else {
2007                         unsigned int ea_size = estimate_ea_size(conn, NULL,
2008                                                                 smb_fname);
2009                         SIVAL(p,0,ea_size); /* Extended attributes */
2010                 }
2011                 p += 4;
2012                 SIVAL(p,0,0); p += 4; /* Unknown - reserved ? */
2013                 SBVAL(p,0,file_index); p += 8;
2014                 len = srvstr_push(base_data, flags2, p,
2015                                   fname, PTR_DIFF(end_data, p),
2016                                   STR_TERMINATE_ASCII);
2017                 SIVAL(q, 0, len);
2018                 p += len;
2019
2020                 len = PTR_DIFF(p, pdata);
2021                 pad = (len + (align-1)) & ~(align-1);
2022                 /*
2023                  * offset to the next entry, the caller
2024                  * will overwrite it for the last entry
2025                  * that's why we always include the padding
2026                  */
2027                 SIVAL(pdata,0,pad);
2028                 /*
2029                  * set padding to zero
2030                  */
2031                 if (do_pad) {
2032                         memset(p, 0, pad - len);
2033                         p = pdata + pad;
2034                 } else {
2035                         p = pdata + len;
2036                 }
2037                 break;
2038
2039         case SMB_FIND_ID_BOTH_DIRECTORY_INFO:
2040                 DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_ID_BOTH_DIRECTORY_INFO\n"));
2041                 was_8_3 = mangle_is_8_3(fname, True, conn->params);
2042                 p += 4;
2043                 SIVAL(p,0,reskey); p += 4;
2044                 put_long_date_timespec(conn->ts_res,p,create_date_ts); p += 8;
2045                 put_long_date_timespec(conn->ts_res,p,adate_ts); p += 8;
2046                 put_long_date_timespec(conn->ts_res,p,mdate_ts); p += 8;
2047                 put_long_date_timespec(conn->ts_res,p,cdate_ts); p += 8;
2048                 SOFF_T(p,0,file_size); p += 8;
2049                 SOFF_T(p,0,allocation_size); p += 8;
2050                 SIVAL(p,0,mode); p += 4;
2051                 q = p; p += 4; /* q is placeholder for name length */
2052                 if (mode & FILE_ATTRIBUTE_REPARSE_POINT) {
2053                         SIVAL(p, 0, IO_REPARSE_TAG_DFS);
2054                 } else {
2055                         unsigned int ea_size = estimate_ea_size(conn, NULL,
2056                                                                 smb_fname);
2057                         SIVAL(p,0,ea_size); /* Extended attributes */
2058                 }
2059                 p += 4;
2060                 /* Clear the short name buffer. This is
2061                  * IMPORTANT as not doing so will trigger
2062                  * a Win2k client bug. JRA.
2063                  */
2064                 if (!was_8_3 && check_mangled_names) {
2065                         char mangled_name[13]; /* mangled 8.3 name. */
2066                         if (!name_to_8_3(fname,mangled_name,True,
2067                                         conn->params)) {
2068                                 /* Error - mangle failed ! */
2069                                 memset(mangled_name,'\0',12);
2070                         }
2071                         mangled_name[12] = 0;
2072                         len = srvstr_push(base_data, flags2,
2073                                           p+2, mangled_name, 24,
2074                                           STR_UPPER|STR_UNICODE);
2075                         SSVAL(p, 0, len);
2076                         if (len < 24) {
2077                                 memset(p + 2 + len,'\0',24 - len);
2078                         }
2079                         SSVAL(p, 0, len);
2080                 } else {
2081                         memset(p,'\0',26);
2082                 }
2083                 p += 26;
2084                 SSVAL(p,0,0); p += 2; /* Reserved ? */
2085                 SBVAL(p,0,file_index); p += 8;
2086                 len = srvstr_push(base_data, flags2, p,
2087                                   fname, PTR_DIFF(end_data, p),
2088                                   STR_TERMINATE_ASCII);
2089                 SIVAL(q,0,len);
2090                 p += len;
2091
2092                 len = PTR_DIFF(p, pdata);
2093                 pad = (len + (align-1)) & ~(align-1);
2094                 /*
2095                  * offset to the next entry, the caller
2096                  * will overwrite it for the last entry
2097                  * that's why we always include the padding
2098                  */
2099                 SIVAL(pdata,0,pad);
2100                 /*
2101                  * set padding to zero
2102                  */
2103                 if (do_pad) {
2104                         memset(p, 0, pad - len);
2105                         p = pdata + pad;
2106                 } else {
2107                         p = pdata + len;
2108                 }
2109                 break;
2110
2111         /* CIFS UNIX Extension. */
2112
2113         case SMB_FIND_FILE_UNIX:
2114         case SMB_FIND_FILE_UNIX_INFO2:
2115                 p+= 4;
2116                 SIVAL(p,0,reskey); p+= 4;    /* Used for continuing search. */
2117
2118                 /* Begin of SMB_QUERY_FILE_UNIX_BASIC */
2119
2120                 if (info_level == SMB_FIND_FILE_UNIX) {
2121                         DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_UNIX\n"));
2122                         p = store_file_unix_basic(conn, p,
2123                                                 NULL, &smb_fname->st);
2124                         len = srvstr_push(base_data, flags2, p,
2125                                           fname, PTR_DIFF(end_data, p),
2126                                           STR_TERMINATE);
2127                 } else {
2128                         DEBUG(10,("smbd_marshall_dir_entry: SMB_FIND_FILE_UNIX_INFO2\n"));
2129                         p = store_file_unix_basic_info2(conn, p,
2130                                                 NULL, &smb_fname->st);
2131                         nameptr = p;
2132                         p += 4;
2133                         len = srvstr_push(base_data, flags2, p, fname,
2134                                           PTR_DIFF(end_data, p), 0);
2135                         SIVAL(nameptr, 0, len);
2136                 }
2137
2138                 p += len;
2139
2140                 len = PTR_DIFF(p, pdata);
2141                 pad = (len + (align-1)) & ~(align-1);
2142                 /*
2143                  * offset to the next entry, the caller
2144                  * will overwrite it for the last entry
2145                  * that's why we always include the padding
2146                  */
2147                 SIVAL(pdata,0,pad);
2148                 /*
2149                  * set padding to zero
2150                  */
2151                 if (do_pad) {
2152                         memset(p, 0, pad - len);
2153                         p = pdata + pad;
2154                 } else {
2155                         p = pdata + len;
2156                 }
2157                 /* End of SMB_QUERY_FILE_UNIX_BASIC */
2158
2159                 break;
2160
2161         default:
2162                 return false;
2163         }
2164
2165         if (PTR_DIFF(p,pdata) > space_remaining) {
2166                 *out_of_space = true;
2167                 DEBUG(9,("smbd_marshall_dir_entry: out of space "
2168                         "(wanted %u, had %d)\n",
2169                         (unsigned int)PTR_DIFF(p,pdata),
2170                         space_remaining ));
2171                 return false; /* Not finished - just out of space */
2172         }
2173
2174         /* Setup the last entry pointer, as an offset from base_data */
2175         *last_entry_off = PTR_DIFF(last_entry_ptr,base_data);
2176         /* Advance the data pointer to the next slot */
2177         *ppdata = p;
2178
2179         return true;
2180 }
2181
2182 bool smbd_dirptr_lanman2_entry(TALLOC_CTX *ctx,
2183                                connection_struct *conn,
2184                                struct dptr_struct *dirptr,
2185                                uint16 flags2,
2186                                const char *path_mask,
2187                                uint32 dirtype,
2188                                int info_level,
2189                                int requires_resume_key,
2190                                bool dont_descend,
2191                                bool ask_sharemode,
2192                                uint8_t align,
2193                                bool do_pad,
2194                                char **ppdata,
2195                                char *base_data,
2196                                char *end_data,
2197                                int space_remaining,
2198                                bool *out_of_space,
2199                                bool *got_exact_match,
2200                                int *_last_entry_off,
2201                                struct ea_list *name_list)
2202 {
2203         const char *p;
2204         const char *mask = NULL;
2205         long prev_dirpos = 0;
2206         uint32_t mode = 0;
2207         char *fname = NULL;
2208         struct smb_filename *smb_fname = NULL;
2209         struct smbd_dirptr_lanman2_state state;
2210         bool ok;
2211         uint64_t last_entry_off = 0;
2212
2213         ZERO_STRUCT(state);
2214         state.conn = conn;
2215         state.info_level = info_level;
2216         state.check_mangled_names = lp_mangled_names(conn->params);
2217         state.has_wild = dptr_has_wild(dirptr);
2218         state.got_exact_match = false;
2219
2220         *out_of_space = false;
2221         *got_exact_match = false;
2222
2223         p = strrchr_m(path_mask,'/');
2224         if(p != NULL) {
2225                 if(p[1] == '\0') {
2226                         mask = "*.*";
2227                 } else {
2228                         mask = p+1;
2229                 }
2230         } else {
2231                 mask = path_mask;
2232         }
2233
2234         ok = smbd_dirptr_get_entry(ctx,
2235                                    dirptr,
2236                                    mask,
2237                                    dirtype,
2238                                    dont_descend,
2239                                    ask_sharemode,
2240                                    smbd_dirptr_lanman2_match_fn,
2241                                    smbd_dirptr_lanman2_mode_fn,
2242                                    &state,
2243                                    &fname,
2244                                    &smb_fname,
2245                                    &mode,
2246                                    &prev_dirpos);
2247         if (!ok) {
2248                 return false;
2249         }
2250
2251         *got_exact_match = state.got_exact_match;
2252
2253         ok = smbd_marshall_dir_entry(ctx,
2254                                      conn,
2255                                      flags2,
2256                                      info_level,
2257                                      name_list,
2258                                      state.check_mangled_names,
2259                                      requires_resume_key,
2260                                      mode,
2261                                      fname,
2262                                      smb_fname,
2263                                      space_remaining,
2264                                      align,
2265                                      do_pad,
2266                                      base_data,
2267                                      ppdata,
2268                                      end_data,
2269                                      out_of_space,
2270                                      &last_entry_off);
2271         TALLOC_FREE(fname);
2272         TALLOC_FREE(smb_fname);
2273         if (*out_of_space) {
2274                 dptr_SeekDir(dirptr, prev_dirpos);
2275                 return false;
2276         }
2277         if (!ok) {
2278                 return false;
2279         }
2280
2281         *_last_entry_off = last_entry_off;
2282         return true;
2283 }
2284
2285 static bool get_lanman2_dir_entry(TALLOC_CTX *ctx,
2286                                 connection_struct *conn,
2287                                 struct dptr_struct *dirptr,
2288                                 uint16 flags2,
2289                                 const char *path_mask,
2290                                 uint32 dirtype,
2291                                 int info_level,
2292                                 bool requires_resume_key,
2293                                 bool dont_descend,
2294                                 bool ask_sharemode,
2295                                 char **ppdata,
2296                                 char *base_data,
2297                                 char *end_data,
2298                                 int space_remaining,
2299                                 bool *out_of_space,
2300                                 bool *got_exact_match,
2301                                 int *last_entry_off,
2302                                 struct ea_list *name_list)
2303 {
2304         uint8_t align = 4;
2305         const bool do_pad = true;
2306
2307         if (info_level >= 1 && info_level <= 3) {
2308                 /* No alignment on earlier info levels. */
2309                 align = 1;
2310         }
2311
2312         return smbd_dirptr_lanman2_entry(ctx, conn, dirptr, flags2,
2313                                          path_mask, dirtype, info_level,
2314                                          requires_resume_key, dont_descend, ask_sharemode,
2315                                          align, do_pad,
2316                                          ppdata, base_data, end_data,
2317                                          space_remaining,
2318                                          out_of_space, got_exact_match,
2319                                          last_entry_off, name_list);
2320 }
2321
2322 /****************************************************************************
2323  Reply to a TRANS2_FINDFIRST.
2324 ****************************************************************************/
2325
2326 static void call_trans2findfirst(connection_struct *conn,
2327                                  struct smb_request *req,
2328                                  char **pparams, int total_params,
2329                                  char **ppdata, int total_data,
2330                                  unsigned int max_data_bytes)
2331 {
2332         /* We must be careful here that we don't return more than the
2333                 allowed number of data bytes. If this means returning fewer than
2334                 maxentries then so be it. We assume that the redirector has
2335                 enough room for the fixed number of parameter bytes it has
2336                 requested. */
2337         struct smb_filename *smb_dname = NULL;
2338         char *params = *pparams;
2339         char *pdata = *ppdata;
2340         char *data_end;
2341         uint32 dirtype;
2342         int maxentries;
2343         uint16 findfirst_flags;
2344         bool close_after_first;
2345         bool close_if_end;
2346         bool requires_resume_key;
2347         int info_level;
2348         char *directory = NULL;
2349         char *mask = NULL;
2350         char *p;
2351         int last_entry_off=0;
2352         int dptr_num = -1;
2353         int numentries = 0;
2354         int i;
2355         bool finished = False;
2356         bool dont_descend = False;
2357         bool out_of_space = False;
2358         int space_remaining;
2359         bool mask_contains_wcard = False;
2360         struct ea_list *ea_list = NULL;
2361         NTSTATUS ntstatus = NT_STATUS_OK;
2362         bool ask_sharemode = lp_parm_bool(SNUM(conn), "smbd", "search ask sharemode", true);
2363         TALLOC_CTX *ctx = talloc_tos();
2364         struct dptr_struct *dirptr = NULL;
2365         struct smbd_server_connection *sconn = req->sconn;
2366         uint32_t ucf_flags = (UCF_SAVE_LCOMP | UCF_ALWAYS_ALLOW_WCARD_LCOMP);
2367         bool backup_priv = false;
2368
2369         if (total_params < 13) {
2370                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2371                 goto out;
2372         }
2373
2374         dirtype = SVAL(params,0);
2375         maxentries = SVAL(params,2);
2376         findfirst_flags = SVAL(params,4);
2377         close_after_first = (findfirst_flags & FLAG_TRANS2_FIND_CLOSE);
2378         close_if_end = (findfirst_flags & FLAG_TRANS2_FIND_CLOSE_IF_END);
2379         requires_resume_key = (findfirst_flags & FLAG_TRANS2_FIND_REQUIRE_RESUME);
2380         backup_priv = ((findfirst_flags & FLAG_TRANS2_FIND_BACKUP_INTENT) &&
2381                                 security_token_has_privilege(get_current_nttok(conn),
2382                                                 SEC_PRIV_BACKUP));
2383
2384         info_level = SVAL(params,6);
2385
2386         DEBUG(3,("call_trans2findfirst: dirtype = %x, maxentries = %d, close_after_first=%d, \
2387 close_if_end = %d requires_resume_key = %d backup_priv = %d level = 0x%x, max_data_bytes = %d\n",
2388                 (unsigned int)dirtype, maxentries, close_after_first, close_if_end, requires_resume_key,
2389                 (int)backup_priv,
2390                 info_level, max_data_bytes));
2391
2392         if (!maxentries) {
2393                 /* W2K3 seems to treat zero as 1. */
2394                 maxentries = 1;
2395         }
2396
2397         switch (info_level) {
2398                 case SMB_FIND_INFO_STANDARD:
2399                 case SMB_FIND_EA_SIZE:
2400                 case SMB_FIND_EA_LIST:
2401                 case SMB_FIND_FILE_DIRECTORY_INFO:
2402                 case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
2403                 case SMB_FIND_FILE_NAMES_INFO:
2404                 case SMB_FIND_FILE_BOTH_DIRECTORY_INFO:
2405                 case SMB_FIND_ID_FULL_DIRECTORY_INFO:
2406                 case SMB_FIND_ID_BOTH_DIRECTORY_INFO:
2407                         break;
2408                 case SMB_FIND_FILE_UNIX:
2409                 case SMB_FIND_FILE_UNIX_INFO2:
2410                         /* Always use filesystem for UNIX mtime query. */
2411                         ask_sharemode = false;
2412                         if (!lp_unix_extensions()) {
2413                                 reply_nterror(req, NT_STATUS_INVALID_LEVEL);
2414                                 goto out;
2415                         }
2416                         ucf_flags |= UCF_UNIX_NAME_LOOKUP;
2417                         break;
2418                 default:
2419                         reply_nterror(req, NT_STATUS_INVALID_LEVEL);
2420                         goto out;
2421         }
2422
2423         srvstr_get_path_wcard(ctx, params, req->flags2, &directory,
2424                               params+12, total_params - 12,
2425                               STR_TERMINATE, &ntstatus, &mask_contains_wcard);
2426         if (!NT_STATUS_IS_OK(ntstatus)) {
2427                 reply_nterror(req, ntstatus);
2428                 goto out;
2429         }
2430
2431         if (backup_priv) {
2432                 become_root();
2433                 ntstatus = filename_convert_with_privilege(ctx,
2434                                 conn,
2435                                 req,
2436                                 directory,
2437                                 ucf_flags,
2438                                 &mask_contains_wcard,
2439                                 &smb_dname);
2440         } else {
2441                 ntstatus = filename_convert(ctx, conn,
2442                                     req->flags2 & FLAGS2_DFS_PATHNAMES,
2443                                     directory,
2444                                     ucf_flags,
2445                                     &mask_contains_wcard,
2446                                     &smb_dname);
2447         }
2448
2449         if (!NT_STATUS_IS_OK(ntstatus)) {
2450                 if (NT_STATUS_EQUAL(ntstatus,NT_STATUS_PATH_NOT_COVERED)) {
2451                         reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
2452                                         ERRSRV, ERRbadpath);
2453                         goto out;
2454                 }
2455                 reply_nterror(req, ntstatus);
2456                 goto out;
2457         }
2458
2459         mask = smb_dname->original_lcomp;
2460
2461         directory = smb_dname->base_name;
2462
2463         p = strrchr_m(directory,'/');
2464         if(p == NULL) {
2465                 /* Windows and OS/2 systems treat search on the root '\' as if it were '\*' */
2466                 if((directory[0] == '.') && (directory[1] == '\0')) {
2467                         mask = talloc_strdup(ctx,"*");
2468                         if (!mask) {
2469                                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2470                                 goto out;
2471                         }
2472                         mask_contains_wcard = True;
2473                 }
2474         } else {
2475                 *p = 0;
2476         }
2477
2478         if (p == NULL || p == directory) {
2479                 /* Ensure we don't have a directory name of "". */
2480                 directory = talloc_strdup(talloc_tos(), ".");
2481                 if (!directory) {
2482                         reply_nterror(req, NT_STATUS_NO_MEMORY);
2483                         goto out;
2484                 }
2485         }
2486
2487         DEBUG(5,("dir=%s, mask = %s\n",directory, mask));
2488
2489         if (info_level == SMB_FIND_EA_LIST) {
2490                 uint32 ea_size;
2491
2492                 if (total_data < 4) {
2493                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2494                         goto out;
2495                 }
2496
2497                 ea_size = IVAL(pdata,0);
2498                 if (ea_size != total_data) {
2499                         DEBUG(4,("call_trans2findfirst: Rejecting EA request with incorrect \
2500 total_data=%u (should be %u)\n", (unsigned int)total_data, (unsigned int)IVAL(pdata,0) ));
2501                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2502                         goto out;
2503                 }
2504
2505                 if (!lp_ea_support(SNUM(conn))) {
2506                         reply_nterror(req, NT_STATUS_EAS_NOT_SUPPORTED);
2507                         goto out;
2508                 }
2509
2510                 /* Pull out the list of names. */
2511                 ea_list = read_ea_name_list(ctx, pdata + 4, ea_size - 4);
2512                 if (!ea_list) {
2513                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2514                         goto out;
2515                 }
2516         }
2517
2518         if (max_data_bytes + DIR_ENTRY_SAFETY_MARGIN < max_data_bytes) {
2519                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2520                 goto out;
2521         }
2522
2523         *ppdata = (char *)SMB_REALLOC(
2524                 *ppdata, max_data_bytes + DIR_ENTRY_SAFETY_MARGIN);
2525         if(*ppdata == NULL ) {
2526                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2527                 goto out;
2528         }
2529         pdata = *ppdata;
2530         data_end = pdata + max_data_bytes + DIR_ENTRY_SAFETY_MARGIN - 1;
2531
2532         /* Realloc the params space */
2533         *pparams = (char *)SMB_REALLOC(*pparams, 10);
2534         if (*pparams == NULL) {
2535                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2536                 goto out;
2537         }
2538         params = *pparams;
2539
2540         /* Save the wildcard match and attribs we are using on this directory -
2541                 needed as lanman2 assumes these are being saved between calls */
2542
2543         ntstatus = dptr_create(conn,
2544                                 req,
2545                                 NULL, /* fsp */
2546                                 directory,
2547                                 False,
2548                                 True,
2549                                 req->smbpid,
2550                                 mask,
2551                                 mask_contains_wcard,
2552                                 dirtype,
2553                                 &dirptr);
2554
2555         if (!NT_STATUS_IS_OK(ntstatus)) {
2556                 reply_nterror(req, ntstatus);
2557                 goto out;
2558         }
2559
2560         if (backup_priv) {
2561                 /* Remember this in case we have
2562                    to do a findnext. */
2563                 dptr_set_priv(dirptr);
2564         }
2565
2566         dptr_num = dptr_dnum(dirptr);
2567         DEBUG(4,("dptr_num is %d, wcard = %s, attr = %d\n", dptr_num, mask, dirtype));
2568
2569         /* Initialize per TRANS2_FIND_FIRST operation data */
2570         dptr_init_search_op(dirptr);
2571
2572         /* We don't need to check for VOL here as this is returned by
2573                 a different TRANS2 call. */
2574
2575         DEBUG(8,("dirpath=<%s> dontdescend=<%s>\n",
2576                  directory,lp_dont_descend(ctx, SNUM(conn))));
2577         if (in_list(directory,lp_dont_descend(ctx, SNUM(conn)),conn->case_sensitive))
2578                 dont_descend = True;
2579
2580         p = pdata;
2581         space_remaining = max_data_bytes;
2582         out_of_space = False;
2583
2584         for (i=0;(i<maxentries) && !finished && !out_of_space;i++) {
2585                 bool got_exact_match = False;
2586
2587                 /* this is a heuristic to avoid seeking the dirptr except when
2588                         absolutely necessary. It allows for a filename of about 40 chars */
2589                 if (space_remaining < DIRLEN_GUESS && numentries > 0) {
2590                         out_of_space = True;
2591                         finished = False;
2592                 } else {
2593                         finished = !get_lanman2_dir_entry(ctx,
2594                                         conn,
2595                                         dirptr,
2596                                         req->flags2,
2597                                         mask,dirtype,info_level,
2598                                         requires_resume_key,dont_descend,
2599                                         ask_sharemode,
2600                                         &p,pdata,data_end,
2601                                         space_remaining, &out_of_space,
2602                                         &got_exact_match,
2603                                         &last_entry_off, ea_list);
2604                 }
2605
2606                 if (finished && out_of_space)
2607                         finished = False;
2608
2609                 if (!finished && !out_of_space)
2610                         numentries++;
2611
2612                 /*
2613                  * As an optimisation if we know we aren't looking
2614                  * for a wildcard name (ie. the name matches the wildcard exactly)
2615                  * then we can finish on any (first) match.
2616                  * This speeds up large directory searches. JRA.
2617                  */
2618
2619                 if(got_exact_match)
2620                         finished = True;
2621
2622                 /* Ensure space_remaining never goes -ve. */
2623                 if (PTR_DIFF(p,pdata) > max_data_bytes) {
2624                         space_remaining = 0;
2625                         out_of_space = true;
2626                 } else {
2627                         space_remaining = max_data_bytes - PTR_DIFF(p,pdata);
2628                 }
2629         }
2630
2631         /* Check if we can close the dirptr */
2632         if(close_after_first || (finished && close_if_end)) {
2633                 DEBUG(5,("call_trans2findfirst - (2) closing dptr_num %d\n", dptr_num));
2634                 dptr_close(sconn, &dptr_num);
2635         }
2636
2637         /*
2638          * If there are no matching entries we must return ERRDOS/ERRbadfile -
2639          * from observation of NT. NB. This changes to ERRDOS,ERRnofiles if
2640          * the protocol level is less than NT1. Tested with smbclient. JRA.
2641          * This should fix the OS/2 client bug #2335.
2642          */
2643
2644         if(numentries == 0) {
2645                 dptr_close(sconn, &dptr_num);
2646                 if (get_Protocol() < PROTOCOL_NT1) {
2647                         reply_force_doserror(req, ERRDOS, ERRnofiles);
2648                         goto out;
2649                 } else {
2650                         reply_botherror(req, NT_STATUS_NO_SUCH_FILE,
2651                                         ERRDOS, ERRbadfile);
2652                         goto out;
2653                 }
2654         }
2655
2656         /* At this point pdata points to numentries directory entries. */
2657
2658         /* Set up the return parameter block */
2659         SSVAL(params,0,dptr_num);
2660         SSVAL(params,2,numentries);
2661         SSVAL(params,4,finished);
2662         SSVAL(params,6,0); /* Never an EA error */
2663         SSVAL(params,8,last_entry_off);
2664
2665         send_trans2_replies(conn, req, NT_STATUS_OK, params, 10, pdata, PTR_DIFF(p,pdata),
2666                             max_data_bytes);
2667
2668         if ((! *directory) && dptr_path(sconn, dptr_num)) {
2669                 directory = talloc_strdup(talloc_tos(),dptr_path(sconn, dptr_num));
2670                 if (!directory) {
2671                         reply_nterror(req, NT_STATUS_NO_MEMORY);
2672                 }
2673         }
2674
2675         DEBUG( 4, ( "%s mask=%s directory=%s dirtype=%d numentries=%d\n",
2676                 smb_fn_name(req->cmd),
2677                 mask, directory, dirtype, numentries ) );
2678
2679         /*
2680          * Force a name mangle here to ensure that the
2681          * mask as an 8.3 name is top of the mangled cache.
2682          * The reasons for this are subtle. Don't remove
2683          * this code unless you know what you are doing
2684          * (see PR#13758). JRA.
2685          */
2686
2687         if(!mangle_is_8_3_wildcards( mask, False, conn->params)) {
2688                 char mangled_name[13];
2689                 name_to_8_3(mask, mangled_name, True, conn->params);
2690         }
2691  out:
2692
2693         if (backup_priv) {
2694                 unbecome_root();
2695         }
2696
2697         TALLOC_FREE(smb_dname);
2698         return;
2699 }
2700
2701 /****************************************************************************
2702  Reply to a TRANS2_FINDNEXT.
2703 ****************************************************************************/
2704
2705 static void call_trans2findnext(connection_struct *conn,
2706                                 struct smb_request *req,
2707                                 char **pparams, int total_params,
2708                                 char **ppdata, int total_data,
2709                                 unsigned int max_data_bytes)
2710 {
2711         /* We must be careful here that we don't return more than the
2712                 allowed number of data bytes. If this means returning fewer than
2713                 maxentries then so be it. We assume that the redirector has
2714                 enough room for the fixed number of parameter bytes it has
2715                 requested. */
2716         char *params = *pparams;
2717         char *pdata = *ppdata;
2718         char *data_end;
2719         int dptr_num;
2720         int maxentries;
2721         uint16 info_level;
2722         uint32 resume_key;
2723         uint16 findnext_flags;
2724         bool close_after_request;
2725         bool close_if_end;
2726         bool requires_resume_key;
2727         bool continue_bit;
2728         bool mask_contains_wcard = False;
2729         char *resume_name = NULL;
2730         const char *mask = NULL;
2731         const char *directory = NULL;
2732         char *p = NULL;
2733         uint16 dirtype;
2734         int numentries = 0;
2735         int i, last_entry_off=0;
2736         bool finished = False;
2737         bool dont_descend = False;
2738         bool out_of_space = False;
2739         int space_remaining;
2740         struct ea_list *ea_list = NULL;
2741         NTSTATUS ntstatus = NT_STATUS_OK;
2742         bool ask_sharemode = lp_parm_bool(SNUM(conn), "smbd", "search ask sharemode", true);
2743         TALLOC_CTX *ctx = talloc_tos();
2744         struct dptr_struct *dirptr;
2745         struct smbd_server_connection *sconn = req->sconn;
2746         bool backup_priv = false; 
2747
2748         if (total_params < 13) {
2749                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2750                 return;
2751         }
2752
2753         dptr_num = SVAL(params,0);
2754         maxentries = SVAL(params,2);
2755         info_level = SVAL(params,4);
2756         resume_key = IVAL(params,6);
2757         findnext_flags = SVAL(params,10);
2758         close_after_request = (findnext_flags & FLAG_TRANS2_FIND_CLOSE);
2759         close_if_end = (findnext_flags & FLAG_TRANS2_FIND_CLOSE_IF_END);
2760         requires_resume_key = (findnext_flags & FLAG_TRANS2_FIND_REQUIRE_RESUME);
2761         continue_bit = (findnext_flags & FLAG_TRANS2_FIND_CONTINUE);
2762
2763         if (!continue_bit) {
2764                 /* We only need resume_name if continue_bit is zero. */
2765                 srvstr_get_path_wcard(ctx, params, req->flags2, &resume_name,
2766                               params+12,
2767                               total_params - 12, STR_TERMINATE, &ntstatus,
2768                               &mask_contains_wcard);
2769                 if (!NT_STATUS_IS_OK(ntstatus)) {
2770                         /* Win9x or OS/2 can send a resume name of ".." or ".". This will cause the parser to
2771                            complain (it thinks we're asking for the directory above the shared
2772                            path or an invalid name). Catch this as the resume name is only compared, never used in
2773                            a file access. JRA. */
2774                         srvstr_pull_talloc(ctx, params, req->flags2,
2775                                 &resume_name, params+12,
2776                                 total_params - 12,
2777                                 STR_TERMINATE);
2778
2779                         if (!resume_name || !(ISDOT(resume_name) || ISDOTDOT(resume_name))) {
2780                                 reply_nterror(req, ntstatus);
2781                                 return;
2782                         }
2783                 }
2784         }
2785
2786         DEBUG(3,("call_trans2findnext: dirhandle = %d, max_data_bytes = %d, maxentries = %d, \
2787 close_after_request=%d, close_if_end = %d requires_resume_key = %d \
2788 resume_key = %d resume name = %s continue=%d level = %d\n",
2789                 dptr_num, max_data_bytes, maxentries, close_after_request, close_if_end, 
2790                 requires_resume_key, resume_key,
2791                 resume_name ? resume_name : "(NULL)", continue_bit, info_level));
2792
2793         if (!maxentries) {
2794                 /* W2K3 seems to treat zero as 1. */
2795                 maxentries = 1;
2796         }
2797
2798         switch (info_level) {
2799                 case SMB_FIND_INFO_STANDARD:
2800                 case SMB_FIND_EA_SIZE:
2801                 case SMB_FIND_EA_LIST:
2802                 case SMB_FIND_FILE_DIRECTORY_INFO:
2803                 case SMB_FIND_FILE_FULL_DIRECTORY_INFO:
2804                 case SMB_FIND_FILE_NAMES_INFO:
2805                 case SMB_FIND_FILE_BOTH_DIRECTORY_INFO:
2806                 case SMB_FIND_ID_FULL_DIRECTORY_INFO:
2807                 case SMB_FIND_ID_BOTH_DIRECTORY_INFO:
2808                         break;
2809                 case SMB_FIND_FILE_UNIX:
2810                 case SMB_FIND_FILE_UNIX_INFO2:
2811                         /* Always use filesystem for UNIX mtime query. */
2812                         ask_sharemode = false;
2813                         if (!lp_unix_extensions()) {
2814                                 reply_nterror(req, NT_STATUS_INVALID_LEVEL);
2815                                 return;
2816                         }
2817                         break;
2818                 default:
2819                         reply_nterror(req, NT_STATUS_INVALID_LEVEL);
2820                         return;
2821         }
2822
2823         if (info_level == SMB_FIND_EA_LIST) {
2824                 uint32 ea_size;
2825
2826                 if (total_data < 4) {
2827                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2828                         return;
2829                 }
2830
2831                 ea_size = IVAL(pdata,0);
2832                 if (ea_size != total_data) {
2833                         DEBUG(4,("call_trans2findnext: Rejecting EA request with incorrect \
2834 total_data=%u (should be %u)\n", (unsigned int)total_data, (unsigned int)IVAL(pdata,0) ));
2835                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2836                         return;
2837                 }
2838
2839                 if (!lp_ea_support(SNUM(conn))) {
2840                         reply_nterror(req, NT_STATUS_EAS_NOT_SUPPORTED);
2841                         return;
2842                 }
2843
2844                 /* Pull out the list of names. */
2845                 ea_list = read_ea_name_list(ctx, pdata + 4, ea_size - 4);
2846                 if (!ea_list) {
2847                         reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2848                         return;
2849                 }
2850         }
2851
2852         if (max_data_bytes + DIR_ENTRY_SAFETY_MARGIN < max_data_bytes) {
2853                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2854                 return;
2855         }
2856
2857         *ppdata = (char *)SMB_REALLOC(
2858                 *ppdata, max_data_bytes + DIR_ENTRY_SAFETY_MARGIN);
2859         if(*ppdata == NULL) {
2860                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2861                 return;
2862         }
2863
2864         pdata = *ppdata;
2865         data_end = pdata + max_data_bytes + DIR_ENTRY_SAFETY_MARGIN - 1;
2866
2867         /* Realloc the params space */
2868         *pparams = (char *)SMB_REALLOC(*pparams, 6*SIZEOFWORD);
2869         if(*pparams == NULL ) {
2870                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2871                 return;
2872         }
2873
2874         params = *pparams;
2875
2876         /* Check that the dptr is valid */
2877         if(!(dirptr = dptr_fetch_lanman2(sconn, dptr_num))) {
2878                 reply_nterror(req, STATUS_NO_MORE_FILES);
2879                 return;
2880         }
2881
2882         directory = dptr_path(sconn, dptr_num);
2883
2884         /* Get the wildcard mask from the dptr */
2885         if((mask = dptr_wcard(sconn, dptr_num))== NULL) {
2886                 DEBUG(2,("dptr_num %d has no wildcard\n", dptr_num));
2887                 reply_nterror(req, STATUS_NO_MORE_FILES);
2888                 return;
2889         }
2890
2891         /* Get the attr mask from the dptr */
2892         dirtype = dptr_attr(sconn, dptr_num);
2893
2894         backup_priv = dptr_get_priv(dirptr);
2895
2896         DEBUG(3,("dptr_num is %d, mask = %s, attr = %x, dirptr=(0x%lX,%ld) "
2897                 "backup_priv = %d\n",
2898                 dptr_num, mask, dirtype,
2899                 (long)dirptr,
2900                 dptr_TellDir(dirptr),
2901                 (int)backup_priv));
2902
2903         /* Initialize per TRANS2_FIND_NEXT operation data */
2904         dptr_init_search_op(dirptr);
2905
2906         /* We don't need to check for VOL here as this is returned by
2907                 a different TRANS2 call. */
2908
2909         DEBUG(8,("dirpath=<%s> dontdescend=<%s>\n",
2910                  directory,lp_dont_descend(ctx, SNUM(conn))));
2911         if (in_list(directory,lp_dont_descend(ctx, SNUM(conn)),conn->case_sensitive))
2912                 dont_descend = True;
2913
2914         p = pdata;
2915         space_remaining = max_data_bytes;
2916         out_of_space = False;
2917
2918         if (backup_priv) {
2919                 become_root();
2920         }
2921
2922         /*
2923          * Seek to the correct position. We no longer use the resume key but
2924          * depend on the last file name instead.
2925          */
2926
2927         if(!continue_bit && resume_name && *resume_name) {
2928                 SMB_STRUCT_STAT st;
2929
2930                 long current_pos = 0;
2931                 /*
2932                  * Remember, name_to_8_3 is called by
2933                  * get_lanman2_dir_entry(), so the resume name
2934                  * could be mangled. Ensure we check the unmangled name.
2935                  */
2936
2937          &