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